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

Rob Cliffe rob.cliffe at btinternet.com
Mon Jun 14 17:04:37 EDT 2021


This puzzled me, so I played around with it a bit (Python 3.8.3):

n = []
for i in range(3):
     n.append((1,7,-3,None,"x"))
for i in range(3):
     n.append((1,7,-3,None,"x"))
print([id(x) for x in n])

a = 4
n = []
for i in range(3):
     n.append((1,7,-3,a,None,"x"))
for i in range(3):
     n.append((1,7,-3,a,None,"x"))
print([id(x) for x in n])

Output:

[27164832, 27164832, 27164832, 27164832, 27164832, 27164832]
[30065208, 30065496, 30237192, 30239976, 30240024, 30343928]

Evidently the compiler is clever enough to pick out a constant tuple and 
create (or cause to get created) a single instance of it which is used 
when required.  Indeed disassembling the code shows that LOAD_CONST is 
used to get the tuple.  But it obviously can't do that when the tuple 
contains a variable.
Rob Cliffe


On 14/06/2021 20:35, Chris Angelico wrote:
> 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.
>
>>>>> m = [[1,2] for i in range(3)]
>>>>> m
>> [[1, 2], [1, 2], [1, 2]]
>>>>> id(m[0]) == id(m[1])  == id(m[2])
>> False
> These are lists. Each one is distinct. You could change one of them
> and the other two would remain as they are.
>
> ChrisA



More information about the Python-list mailing list