Why the list creates in two different ways? Does it cause by the mutability of its elements? Where the Python document explains it?

Chris Angelico rosuav at gmail.com
Tue Jun 15 05:08:34 EDT 2021


On Tue, Jun 15, 2021 at 6:32 PM Dieter Maurer <dieter at handshake.de> wrote:
>
> Chris Angelico wrote at 2021-6-15 05:35 +1000:
> >On Tue, Jun 15, 2021 at 5:12 AM Jach Feng <jfong at ms4.hinet.net> wrote:
> >>
> >> >>> n = [(1,2) for i in range(3)]
> >> >>> n
> >> [(1, 2), (1, 2), (1, 2)]
> >> >>> id(n[0]) == id(n[1])  == id(n[2])
> >> True
> >
> >This is three tuples. Tuples are immutable and you get three
> >references to the same thing.
>
> In addition: object identity (as revealed by `id(...)`) is
> an implementation detail. Do not rely on it!

Hmm, not always. In this case, object identity isn't guaranteed -
every literal could give you a unique object - but in other cases,
object identity is a language guarantee. For instance:

>>> l = (1, 2) # or [1, 2]
>>> [l for _ in range(10)]
[(1, 2), (1, 2), (1, 2), (1, 2), (1, 2), (1, 2), (1, 2), (1, 2), (1, 2), (1, 2)]
>>> [id(x) for x in _]
[140499111503808, 140499111503808, 140499111503808, 140499111503808,
140499111503808, 140499111503808, 140499111503808, 140499111503808,
140499111503808, 140499111503808]

In this example, it doesn't matter whether it's a list or a tuple (or
anything else) - the IDs are all guaranteed to be the same.

The only thing that's an implementation detail is whether immutable
objects are folded together. You'll find similar situations with
strings, numbers, etc, etc. For example, "name-like" strings are often
interned in CPython, but other strings aren't, so sometimes you might
find different behaviour if you have a space in the string than if you
don't.

ChrisA


More information about the Python-list mailing list