8  Tuples and Sets

Python has different data types to store a collection of items. Tuples and sets are two such data types. Both these data have some unique characteristics that make them useful under different contexts.

8.1 Tuples - the immutable collection

A tuple is a collection of items just like a list; with one important difference that this collection is immutable. In other words, there is no option to add or remove elements form a tuple. A tuple can have elements of same data type or multiple data types. A tuple is denoted by parantheses (()). A tuple can be initialized by putting a comma-separated collection of element within parantheses (or even with paranthesis). The tuple keyword can be used to convert a list to a tuple. Note that when initializing a tuple with single element we need to put a comma after the element. To access an element by its index we can specify index in square brackets after the tuple name. A slice of a tuple returns a tuple.

fruits = ("apple", "banana", "mango")
print(fruits)
print(type(fruits))
print(fruits[1])
('apple', 'banana', 'mango')
<class 'tuple'>
banana
fruits2 = "pineapple", "cherry"
print(fruits2)
('pineapple', 'cherry')
nums = [1,2,3,4,5]
nums_tuple = tuple(nums)
print(nums_tuple)
(1, 2, 3, 4, 5)

Tuple can be concatenated in the same manner as strings are concatenated. The + and * operators can be used for tuple concatenation.

print(fruits+fruits2)
print(fruits2*3)
('apple', 'banana', 'mango', 'pineapple', 'cherry')
('pineapple', 'cherry', 'pineapple', 'cherry', 'pineapple', 'cherry')

Quiz: What would be the output of the following code. fruits = (“apple”, “mango”) fruits.append(“grapes”)    
print(fruits)

Show answer
Error. Tuples are immutable.

8.1.1 Advantages of Tuples

The fact that tuples are immutable is an important utility feature for this collection data type. For instance, the keys of a dictionary must be of immutable data type, so we can use tuples to have a collection of items as a key.

# a dictionary with keys having studnets name and roll number and 
# values having the subjects taken.
students_data = {('Sam', 102): ['Physics', 'Maths', 'Chemistry'],
         ('Mohan', 103): ['Physics', 'Chemistry', 'Biology']}
for k1, v1 in students_data.items():
    print(f'{k1[0]} (Roll No.{k1[1]}) has taken {", ".join(v1)}.')
Sam (Roll No.102) has taken Physics, Maths, Chemistry.
Mohan (Roll No.103) has taken Physics, Chemistry, Biology.

An important point to note here is that when the tuples are used as a dictionary key then all the elements of a tuple should be immutable. If a tuple with an mutable element (e.g. a list) is used as a dictionary key then it would lead to a TypeError.

8.2 Sets and their characteristics

A set is an another data type, just like lists and tuples, that can be used to store a collection of items. A set object can be initialized using the set function or using curly braces {} with elements inside. Note that using empty curly braces would initialize a dict object. The set function take a list as an argument for initializing a set. A notable difference between sets and other collections is that in sets the items are unordered. This implies that we cannot access individual elements of a set by their indices.

Following are characteristics of sets: - Elements in a set are unordered and duplicate elements are not allowed. - Elements in a set must be of immutable data types only. - Elements can be added to and removed from a set.

a = {"apple", "banana", "mango"}
print(type(a))
for element in a:
    print(element)
<class 'set'>
banana
mango
apple

The add and update functions can be used to add one or multiple elements to a set, respectively. To remove an element from a set, discard or remove functions can be used with element as an argument. The former would leave the set unchanged if an element is not present in that set, while the later would lead to an error.

a.add("cherry")
print(a)
a.remove("cherry")
print(a)
{'banana', 'mango', 'apple', 'cherry'}
{'banana', 'mango', 'apple'}

8.2.1 Set operations

We can apply different logical operations to parse content of multiple sets. For instance, to get all the elements present in one set and not present in another set, we can use the minus - operator. Similarly, we can get the union and intersection of two sets using the | and & operators respectively. The carrot (^) operator return the unique elements in the two sets.

a = {"apple", "banana", "mango"}
b = {"apple", "banana", "cherry"}
print(a,b)
print("Elements present in a and not in b", a-b)
print("Elements present in b and not in a", b-a)
print("Union of sets a and b", a|b)
print("Intersection of sets a and b", a&b)
print("Unique elements in sets a and b", a^b)
{'banana', 'mango', 'apple'} {'banana', 'apple', 'cherry'}
Elements present in a and not in b {'mango'}
Elements present in b and not in a {'cherry'}
Union of sets a and b {'banana', 'mango', 'apple', 'cherry'}
Intersection of sets a and b {'banana', 'apple'}
Unique elements in sets a and b {'mango', 'cherry'}

Quiz: Which of the following expression is equivalent to a^b.
a-b&a+b a-b|b-a a|b-a&b
a&b-a|b

Show answer
a-b|b-a