I was just toying around in the interpreter and ran across something that I do not understand. When I create a tuple with a list as one the elements and then try to update that list, something strange happens. For example, when I run this:
tup = (1,2,3,[4,5])
tup[3] += [6]
I get:
TypeError: 'tuple' object does not support item assignment
Which is exactly what I expected. However then when I reference the tuple again, I get:
>>> tup
(1, 2, 3, [4, 5, 6])
So the list was in fact updated even though python threw an exception. How does that work? I can't imagine a scenario where I would actually want to do something like this, but I still would like to understand what is going on. Thank you.
The key difference between the tuples and lists is that while the tuples are immutable objects the lists are mutable. This means that tuples cannot be changed while the lists can be modified. Tuples are more memory efficient than the lists.
Tuples A Tuple represents a collection of objects that are ordered and immutable (cannot be modified). Tuples allow duplicate members and are indexed.
We consider the tuple as duplicate if all the attribute values of two rows are the same. Redundancies between attributes and duplicate tuples must be detected.
tuple () function can take any iterable as an argument and convert it into a tuple object. As you wish to convert a python list to a tuple, you can pass the entire list as a parameter within the tuple() function, and it will return the tuple data type as an output.
This is actually documented in the Python docs.
EDIT: Here's a summary so that this is a more complete answer.
+=
, Python calls the __iadd__
magic method on the item, then uses the return value in the subsequent item assignment.__iadd__
is equivalent to calling extend
on the list and then returning the list.Therefore, when we call tup[3] += [6]
, it is equivalent to:
result = tup[3].__iadd__([6])
tup[3] = result
From #2, we can determine this is equivalent to:
result = tup[3].extend([6])
tup[3] = result
extend
on the list, and since the list is mutable, it updates. However, the subsequent assignment fails because tuples are immutable, and throws the error.If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With