[Python-ideas] Unpacking iterables for augmented assignment
Steven D'Aprano
steve at pearwood.info
Sun Aug 26 13:45:46 EDT 2018
On Sun, Aug 26, 2018 at 06:19:36PM +0100, Jonathan Fine wrote:
> Finally, here's something that surprised me a little bit
>
> >>> x = [1, 2]; id(x)
> 140161160364616
> >>> x += [3, 4]; id(x)
> 140161160364616
> >>> x = (1, 2); id(x)
> 140161159928520
> >>> x += (3, 4); id(x)
> 140161225906440
>
> Notice that '+=' creates uses the same object when the object is a
> list, but creates a new object. This raises the question: Why and how
> does Python behave in this way?
Lists are mutable and can be modified in place. Tuples are immutable and
cannot be.
By the way: it's not reliable to compare ID numbers for objects which
don't necessarily exist similtaneously. The Python interpreter is
permitted to re-use ID numbers. For example:
py> s = [1, 4]
py> id(s)
3080212620
py> del s
py> s = [-1, 3]
py> id(s)
3080212620
The only reliable use of ID numbers is to compare the ID of objects
which are known to still exist.
--
Steve
More information about the Python-ideas
mailing list