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

html - Sizing a high-res image (~8MB) to display entirely in a small div (circular, diameter 100px) -

java - IntelliJ - No such instance method -

identifier - Is it possible for an html5 document to have two ids? -