python - Locating the first item in a list of lists -


i have scenario:

>>> y=[[1]] >>> y=y*2 >>> y [[1], [1]] >>> y[0].append(2) >>> y [[1, 2], [1, 2]] 

what i'd add 2 first list within outer list i.e. desired output:

[[1, 2], [1]] 

doing:

y=[[1]] y=y*2 

creates list 2 references same list object:

>>> y=[[1]] >>> y=y*2 >>> id(y[0])  # id of first element... 28864920 >>> id(y[1])  # ...is same id of second. 28864920 >>> 

this means that, when modify one, other affected well.


to fix problem, can use list comprehension instead:

>>> y = [[1] _ in xrange(2)]  # use range here if on python 3.x >>> y [[1], [1]] >>> id(y[0])  # id of first element... 28864920 >>> id(y[1])  # ...is different id of second. 28865520 >>> y[0].append(2) >>> y [[1, 2], [1]] >>> 

Comments

Popular posts from this blog

php - regexp cyrillic filename not matches -

c# - OpenXML hanging while writing elements -

sql - Select Query has unexpected multiple records (MS Access) -