Skip to content Skip to sidebar Skip to footer

If In Python I Put A List Inside A Tuple, Can I Safely Change The Contents Of That List?

The value inside the tuple is simply a reference to a list, and if I change the values in the list everything is still in order, right? I want to make sure that if I do this I won'

Solution 1:

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])

Solution 2:

Tuples are immutable - you can't change their structure

>>> a = []
>>> tup = (a,)
>>> tup[0] is a # tup stores the reference to aTrue>>> tup[0] = a # ... but you can't re-assign it later
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
TypeError: 'tuple'object does not support item assignment
>>> tup[0] = 'string'# ... same for all other objects
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
TypeError: 'tuple'object does not support item assignment

or size

>>>del tup[0] # Nuh uh
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
TypeError: 'tuple' object does not support item deletion
>>>id(tup)
139763805156632
>>>tup += ('something',) # works, because it creates a new tuple object:>>>id(tup) # ... the id is different
139763805150344

after you create them.

On the other hand, mutable objects stored in a tuple do not lose their mutability e.g. you can still modify inner lists using list methods:

>>>a = []>>>b, c = (a,), (a,) # references to a, not copies of a>>>b[0].append(1)>>>b
([1],)
>>>c
([1],)

Tuples can store any kind of object, although tuples that contain lists (or any other mutable objects) are not hashable:

>>> hash(b)
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
TypeError: unhashable type: 'list'

The behaviour demonstrated above can indeed lead to confusing errors.

Post a Comment for "If In Python I Put A List Inside A Tuple, Can I Safely Change The Contents Of That List?"