No Fluff Guide to Python - P6 - Tuple & Sets
Imagine you have a shopping list. You can write down all the things you need to buy, like milk, eggs, and bread.
A Python TUPLE is like a shopping list. You can store any kind of data in a list, like numbers, strings, and even other lists. But you CANNOT add and remove items from a list.
TUPLE
- A tuple is like a list
- but it is immutable.
- means that you cannot change the items in a tuple.
- Tuples are created using the ( ) parentheses.
- example
- create a tuple with the items "milk", "eggs", and "bread":
shopping_tuple = ("milk", "eggs", "bread")
tuple = ("linux", "mac")
#Tuples are immutable
You can access the items in a tuple using the [ ] brackets. For example, the following code prints the first item in the tuple:
tuple1=("good",1,2,3,"morning")
print(tuple1[0])
# accessing values using indexing
However, you cannot change the items in a tuple. For example, the following code will give an error:
Immutable: following code doesn't work
tuple[1]="change" ❌
# a value cannot be changed as they are immutable
- Tuples are often used
- when you need to store data that will not change
- example
- store the names of the months of the year
tuple = ("linux", "mac")
#Tuples are immutable
tuple2=("orange","grapes")
print(tuple1+tuple2)
# tuples can be concatenated
tuple1=(1,2,3,4)
tuple1.pop() #tuple cannot be modified ❌
tuple1.append() #tuple cannot be modified ❌
SET
- Imagine you have a collection of unique toys.
- You don't have any duplicates.
- You can put all of your toys in a box and shake it up.
- When you open the box
- the toys will be in a different order
- but you will still have the same number of toys.
- A Python set is like a box of unique toys
- You can store any kind of data in a set
- numbers, strings, and even other sets.
- you cannot have any duplicates in a set.
To create a set, you use the {}
curly braces.
set = {"linux", "mac"}
#Sets are mutable and have no duplicate elements
set1={1,2,3,4,5, 5} print(set1[0])
#sets are unordered, so it doesnot support indexing
set2={3,7,1,6,1}
# sets doesnot allow duplicate values
#-> 3,7,1,6
set1={"water","air","food"}
set1.add("shelter")
# adds an element to the set at random position
print(set1)
set1.add("clothes")
print(set1)
set1.pop()
# removes random element from the set
print(set1)
#Output
#{'shelter', 'food', 'water', 'air'}
#{'shelter', 'food', 'air', 'water', 'clothes'}
#{'food', 'air', 'water', 'clothes'}
Comments
Post a Comment