0

I cannot explain why there is a different behaviour with the same situation.

If I write:

im = (10, 20, [3, 4])
im[2] += [5, 6, 7, 8]

Then as expected I have this: "TypeError: 'tuple' object does not support item assignment".

If I handle the exception:

im = (10, 20, [3, 4])
print("im: {} - id(im): {}".format(im, id(im)))
print("im[2]: {} - id(im[2]: {})".format(im[2],id(im[2])))
try:
    im[2] += [5, 6, 7, 8]
except:
    pass
print("im: {} - id(im): {}".format(im, id(im)))
print("im[2]: {} - id(im[2]: {})".format(im[2],id(im[2])))

The console prints:

im: (10, 20, [3, 4]) - id(im): 1960340013184
im[2]: [3, 4] - id(im[2]: 1960339967232)
im: (10, 20, [3, 4, 5, 6, 7, 8]) - id(im): 1960340013184
im[2]: [3, 4, 5, 6, 7, 8] - id(im[2]: 1960339967232)

So the exception is raised and the list inside the tuple has been modified (even if the tuple is an immutable object). Until here no problem with this.

But, if I do this:

l=[3,4]
im = (10, 20, l)
l+= [5, 6, 7, 8]

then there is no exception raised, and by checking the id:

l=[3,4]
im = (10, 20, l)
print("im: {} - id(im): {}".format(im, id(im)))
print("l: {} - id(l): {}".format(l,id(l)))

l+= [5, 6, 7, 8]

print("im: {} - id(im): {}".format(im, id(im)))
print("l: {} - id(l): {}".format(l,id(l)))

I get in the console:

im: (10, 20, [3, 4]) - id(im): 2050054668416
l: [3, 4] - id(l): 2050054622528
im: (10, 20, [3, 4, 5, 6, 7, 8]) - id(im): 2050054668416
l: [3, 4, 5, 6, 7, 8] - id(l): 2050054622528 

I don't understand why there is a different behaviour. I was expecting that the exception was raised in both case.

(I'am using Python 3.8.5)

martineau
  • 119,623
  • 25
  • 170
  • 301
Fabio S.
  • 41
  • 2

0 Answers0