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

Jach Feng jfong at ms4.hinet.net
Mon Jun 14 23:18:00 EDT 2021


Chris Angelico 在 2021年6月15日 星期二上午5:23:12 [UTC+8] 的信中寫道:
> On Tue, Jun 15, 2021 at 7:11 AM Rob Cliffe via Python-list 
> <pytho... at python.org> wrote: 
> > 
> > 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.
> Correct. In theory, Python could intern the tuples (as can be done 
> with strings), noticing that it's constructing one that is identical 
> to one it already has, but the effort of doing that is hard to 
> justify. Simpler to just build a brand new tuple every time. 
> 
> ChrisA
>From a user's point, I don't really care how Python creates those instances, either using an already exist one or create a new one, as long as each element (and its sub-element) are independent from each other so a modification of one will not influence the other. The real problem is there are different methods can be used to build it and some will fail in this purpose. The * operator is one of them, but anyone else? I really like to know:-)

--Jach


More information about the Python-list mailing list