python - Locating the first item in a list of lists -
this question has answer here:
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
Post a Comment