3

I'm learning python and I have confusion related to tuples. If elements in tuple are immutable, then how am I able to change a dictionary value present inside a tuple?

E.g.

test_dict = {'a':2,'b':3}

test_tup = (test_dict,3)

test_tup[0]['b'] = 4

If I print test_tup, then b value is updated to 4:

>>> test_tup
({'a': 3, 'b': 4}, 3)

Thanks in advance.

shx2
  • 61,779
  • 13
  • 130
  • 153
spamulap12
  • 97
  • 1
  • 9

2 Answers2

2

Keep in mind that every value in python is a reference to an object.

Thus, instead of thinking about your tuple as a tuple of dicts, for example, think of it as a tuple of references to somethings, where those somethings are dicts. It is not the case that the dicts are inside the tuple. They exist on their own, and the elements of the tuple refer to them.

Now, thinking about it this way, the tuple is immutable. You cannot change its structure/size, and cannot change its elements, meaning you cannot replace one reference with another.

However, the objects being refered to, can be mutable. They exist on their own, regardless of being referred to by the tuple.

If elements in tuple are immutable, then how am I able to change them?

They are not immutable. The tuple is.

shx2
  • 61,779
  • 13
  • 130
  • 153
1

Your tuple only holds a reference to the dict, it cannot track whatever changes you make to things inside it (how would it?).

By immutability, it's understood that you can't do this:

test_tup[0] = {}

This is changing the reference that the tuple holds.

vaultah
  • 44,105
  • 12
  • 114
  • 143
UtsavShah
  • 857
  • 1
  • 9
  • 20
  • meaning you can change a value of a key int he dictionary but you cannot change the dictionary itself to an empty dict. – uniXVanXcel May 22 '17 at 05:41