Dereferencing lists inside list in Python -


when define list in "generic" way:

>>>a=[[]]*3 >>>a [[],[],[]] 

and try append second element of outer list:

>>>a[1].append([0,1]) >>>a [[[0,1]], [[0,1]], [[0,1]]] 

it appends elements of outer list can seen above, due fact elements references same list , not different lists (why work way?). how can create list in same "generic" way, such inner lists different lists , not references. thanks.

you correct, references 1 list.

[[] _ in range(3)] 

is common way create list of independent empty lists. can use xrange on python 2.x, won't make difference if length small in example.

not sure how explain the reason (the reason it's implemented way), can see behavior documented (at least in passing) here:

operation       result                              notes s * n, n * s    n shallow copies of s concatenated  (2) 

the word "shallow" here means that: elements copied reference. "note 2" @ linked page answers question.


Comments

Popular posts from this blog

c# - DetailsView in ASP.Net - How to add another column on the side/add a control in each row? -

javascript - firefox memory leak -

Trying to import CSV file to a SQL Server database using asp.net and c# - can't find what I'm missing -