Tuple ¶
A tuple is just like a list except the content cannot change, meaning I cannot do any mutation (i.e., replace, append, or delete).
In [14]:
Copied!
in_my_closed_pocket = (21, False, None, "apple", 3.14)
print(in_my_closed_pocket)
in_my_closed_pocket = (21, False, None, "apple", 3.14)
print(in_my_closed_pocket)
(21, False, None, 'apple', 3.14)
In [15]:
Copied!
print(in_my_closed_pocket[3])
print(in_my_closed_pocket[3])
apple
In [16]:
Copied!
in_my_closed_pocket.append("wallet")
in_my_closed_pocket.append("wallet")
--------------------------------------------------------------------------- AttributeError Traceback (most recent call last) Cell In[16], line 1 ----> 1 in_my_closed_pocket.append("wallet") AttributeError: 'tuple' object has no attribute 'append'
In [17]:
Copied!
del in_my_closed_pocket[3]
del in_my_closed_pocket[3]
--------------------------------------------------------------------------- TypeError Traceback (most recent call last) Cell In[17], line 1 ----> 1 del in_my_closed_pocket[3] TypeError: 'tuple' object doesn't support item deletion
So why would you want to use a tuple instead of a list?
- If you need a collection of items that should not be changed or modified throughout the program, using a tuple provides immutability. This prevents accidental modifications and ensures data consistency.
- Tuples are generally more memory-efficient than lists because of their immutability. If your data does not need to change, using a tuple can result in better performance.