Tuples
The simplest of the data types. The can store strings, integers and other data types.
Example of a tuple
my_tuple = ("one", "two", "three", "four")
Each value in a tuple is separated by a comma.
We cannot change what is stored in a given tuple.
Each value in the tuple has an index starting from 0. So if we do
print(my_tuple[1]) --> two
We would use a tuple instead of a list if we don’t have a need to change the information in the tuple.
Sets
A collection of unordered unique elements. There cannot be any duplicates in the data and the data itself cannot be changed.
However, the set itself is changeable. We can add or remove items from it.
Examples of sets
# set of integers my_set = {1, 2, 3} print(my_set) ->{1, 2, 3} # set of mixed datatypes my_set = {3.5, "Name", ("a", "b", "c")} print(my_set) ->{3.5, "Name", ("a", "b", "c")}
Sets are mutable. But since they are unordered, indexing has no meaning.
We cannot access or change an element of set using indexing or slicing. Set does not support it.
We can add single element using the add()
method and multiple elements using the update()
method.
A particular item can be removed from set using methods, discard()
and remove()
.
The only difference between the two is that, while using discard()
if the item does not exist in the set, it remains unchanged. But remove()
will raise an error in such condition.
# initialize my_set my_set = {1,3} print(my_set) # add an element # Output: {1, 2, 3} my_set.add(2) print(my_set) # add multiple elements # Output: {1, 2, 3, 4} my_set.update([2,3,4]) print(my_set) # discard an element # Output: {1, 3, 5, 6} my_set.discard(4) print(my_set) # remove an element # Output: {1, 3, 5} my_set.remove(6) print(my_set) # discard an element # not present in my_set # Output: {1, 3, 5} my_set.discard(2) print(my_set)
Similarly, we can remove and return an item using the pop()
method.
Set being unordered, there is no way of determining which item will be popped. It is completely arbitrary.
We can also remove all items from a set using clear()
.