Python Forum
Thread Rating:
  • 0 Vote(s) - 0 Average
  • 1
  • 2
  • 3
  • 4
  • 5
Are tuples immutable?
#11
This can be also worth of knowing about tuples immutability:

>>> spam = (1, [2, 3])
>>> spam[1] += [4, 5]            # will throw error but still mutate list within tuple
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
TypeError: 'tuple' object does not support item assignment
>>> spam
(1, [2, 3, 4, 5])
I'm not 'in'-sane. Indeed, I am so far 'out' of sane that you appear a tiny blip on the distant coast of sanity. Bucky Katt, Get Fuzzy

Da Bishop: There's a dead bishop on the landing. I don't know who keeps bringing them in here. ....but society is to blame.
Reply
#12
@perfringo thanks. It's good to know about details like this.
Reply
#13
(Jan-07-2019, 08:08 AM)python_user_n Wrote: It's good to know about details like this.
Note that this apply only for augmented arithmetic assignment +=, but not for "regular" addition/assignment, i.e.
>>> spam = (1, [2, 3])
>>> spam[1] = spam[1] + [4, 5]
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
TypeError: 'tuple' object does not support item assignment
>>> spam[1]
[2, 3]
>>>
As you can see in this case there is exception and the mutable object is not changed.

Read Why does a_tuple[i] += [‘item’] raise an exception when the addition works? for extended discussion and in-depth explanation.
If you can't explain it to a six year old, you don't understand it yourself, Albert Einstein
How to Ask Questions The Smart Way: link and another link
Create MCV example
Debug small programs

Reply
#14
@buran, Indeed. I remember about '+=' augmented operator when I was comparing it to a '+' concatenation.
Reply


Possibly Related Threads…
Thread Author Replies Views Last Post
  immutable types Skaperen 2 2,066 Jul-09-2021, 01:00 AM
Last Post: Skaperen

Forum Jump:

User Panel Messages

Announcements
Announcement #1 8/1/2020
Announcement #2 8/2/2020
Announcement #3 8/6/2020