Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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't start running into confusing errors.

like image 283
Sophie Avatar asked Oct 08 '14 17:10

Sophie


2 Answers

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])
like image 112
Cory Kramer Avatar answered Oct 19 '22 16:10

Cory Kramer


Tuples are immutable - you can't change their structure

>>> a = []
>>> tup = (a,)
>>> tup[0] is a # tup stores the reference to a
True
>>> 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.

like image 11
vaultah Avatar answered Oct 19 '22 15:10

vaultah