Tuple¶
Tuples are an immutable container type.
They contain a collection of objects. The tuple is a sequence type - this means order matters (and is preserved) and elements can be accessed by index (zero based), slicing, or iteration.
Other common sequence types in Python include lists and strings. Strings, like tuples are immutable, whereas lists are mutable.
Tuples are sometimes presented as immutable lists, but in fact, they could be compared more closely to strings with one major difference: strings are homogeneous sequences, while tuples can be heterogeneous.
A tuple can be defined by using a comma (,).
# A tuple is defined using a comma not by using ().
a = ('a', 10, True)
b = 'b', 20, False
print(type(a), type(b))
<class 'tuple'> <class 'tuple'>
Since tuples are sequence types, we can access items by index, perform slicing operation, iterate over them, unpack them.
a = 'a', 10, True
print("a[2] is : ", a[2])
print("a[1:] is :", a[1:])
print("\nlooping through the tuple is as follows : ")
for i, item in enumerate(a):
print("item [{0}] is : ".format(i), item)
print("\nunpacking the tuple results in : ")
b, c, d = a
print(b)
print(c)
print(d)
a[2] is : True a[1:] is : (10, True) looping through the tuple is as follows : item [0] is : a item [1] is : 10 item [2] is : True unpacking the tuple results in : a 10 True
Tuples are immutable, in the sense that we cannot change the reference of an object in the container and we cannot add or remove objects from the container. This is the same as strings. However we have to be careful when we think about immutability of tuples. The tuple, as a container is immutable, but the elements contained in the tuple may very well be mutable.
a = 3, 4, 6
print("id of a is : \n", id(a))
a[4]=20
id of a is : 2617429228528
--------------------------------------------------------------------------- TypeError Traceback (most recent call last) Cell In[8], line 6 1 a = 3, 4, 6 3 print("id of a is : \n", id(a)) ----> 6 a[4]=20 TypeError: 'tuple' object does not support item assignment
a = a + (3, 4)
print("a is : ", a)
print("id of a now is : \n", id(a))
a is : (3, 4, 6, 3, 4, 3, 4) id of a now is : 2617405591104
# The tuple, as a container is immutable,
# but the elements contained in the tuple may very well be mutable.
lis = [2, 5, 6]
a = (3, lis, 8)
print("a now is : ", a)
print("id of a is : ", id(a))
lis.append(5)
print("a now is : ", a)
print("id of a is : ", id(a))
a now is : (3, [2, 5, 6], 8) id of a is : 2617429818752 a now is : (3, [2, 5, 6, 5], 8) id of a is : 2617429818752
As we can see tuple doesn't support item assignment and in case we mutate the tuple, a new memroy address is assigned.
We can interpret tuples as lightweight data structures where, by convention, the position of the element in the tuple has meaning.
For example, we may elect to represent a point as a tuple, i.e x and y coordinate. so we could you tuple to denote the values.