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 12:20:45 EDT 2021


On Wed, Jun 16, 2021 at 2:18 AM Dieter Maurer <dieter at handshake.de> wrote:
>
> Chris Angelico wrote at 2021-6-15 19:08 +1000:
> >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:
>
> As far as I know, there are no guarantees are the language level.
> There are some (partially documented) implementation details
> for CPython (which is just one possible implementation).

Yes there are - plenty of them :) The example I gave is a language
guarantee. Object identity is maintained in various places, and MUST
be; in fact, I've heard tell that PyPy actually has to do some
shenanigans to ensure that identities can be tracked across certain
types of optimizations (where the object mightn't actually exist
temporarily).

ChrisA


More information about the Python-list mailing list