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
Tue Jun 15 22:07:27 EDT 2021


Greg Ewing 在 2021年6月16日 星期三上午7:11:35 [UTC+8] 的信中寫道:
> On 15/06/21 7:32 pm, Jach Feng wrote: 
> > But usually the list creation is not in simple way:-) for example: 
> >>>> a = [1,2] 
> >>>> m = [a for i in range(3)] 
> >>>> m 
> > [[1, 2], [1, 2], [1, 2]] 
> >>>> id(m[0]) == id(m[1]) == id(m[2]) 
> > True
> The first line is only executed once, so you just get one 
> list object [1, 2]. You then refer to that object three times 
> when you build the outer list. 
> 
> To get three different [1, 2] lists you would need something 
> like this:
> m = [[1,2] for i in range(3)]
> This executes the [1, 2] expression 3 times. Because lists are 
> mutable, you can be sure that this will give you 3 distinct 
> list objects. 
> 
> -- 
> Greg
Yes, I know. Here I just want to show another gutter I had found:-). Anyone else?

--Jach


More information about the Python-list mailing list