If in Python I put a list inside a tuple, can I safely change the contents of that list? [duplicate]

Tuples are immutable, you may not change their contents.

With a list

>>> x = [1,2,3]
>>> x[0] = 5
>>> x
[5, 2, 3]

With a tuple

>>> y = tuple([1,2,3])
>>> y
(1, 2, 3)
>>> y[0] = 5   # Not allowed!

Traceback (most recent call last):
  File "<pyshell#20>", line 1, in <module>
    y[0] = 5
TypeError: 'tuple' object does not support item assignment

But if I understand your question, say you have

>>> a = [1,2,3]
>>> b = [4,5,6]
>>> t = (a,b)
>>> t
([1, 2, 3], [4, 5, 6])

You are allowed to modify the internal lists as

>>> t[0][0] = 5
>>> t
([5, 2, 3], [4, 5, 6])

Leave a Comment