Python: Three Hidden Ways to Create Potential Bugs with Mutable Data Structures (Part III)

May 11, 2021

We were told tuples are immutable data structures when we first learned Python, but this is not absolute. If you pass in a mutable data structure, i.e. a list, into a tuple, you will be able to mutate that mutable data structure within the tuple. Please see the following example:

#a tuple with a list in it
tuple_list = ('apple', 'orange', ['grape', 'watermelon'])
#checking the id of the list item within the tuple

#append an item into the list
('apple', 'orange', ['grape', 'watermelon', 'cucumber'])
#the id of the list item remains the same after mutation

#directly assigning the entire list item within a tuple wouldn't work
a[2] = ['banana']
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
TypeError: 'tuple' object does not support item assignment

The idea is that you should be very careful or perhaps avoid passing in a mutable data structure into a tuple.
Hope you enjoy this week’s Data Hack Tuesday! We will see you next week.