Inner-mosts Lists in Python -
this question has answer here:
why? equal, initially. same operation hey different structures. why 2 methods of constructing nested lists give different results?
>>> lll=[[[[[]]*2 in xrange(2)] b in xrange(2)]] >>> ll=[[[[[]]*2]*2]*2] >>> lll [[[[[], []], [[], []]], [[[], []], [[], []]]]] >>> ll [[[[[], []], [[], []]], [[[], []], [[], []]]]] >>> ll==lll true >>> ll[0][0][0][0]=1 >>> lll[0][0][0][0]=1 >>> ll==lll false #why?
structure
[ [ [ [ [], [] ], [ [], [] ] ], [ [ [], [] ], [ [], [] ] ] ] ]
when use list comprehensions that, new lists created each iteration.
when multiply list, same reference duplicated on , over.
when reference list, means same inner list duplicated on , over.
so, when multiply, there 1 empty list, referenced twice single list, referenced twice single list, referenced twice single list, item in final, outer list.
when use list comprehension, each reference new, different list.
so, when point first item of list containing 2 references empty list different object, see change everywhere list referenced. since it's referenced twice list referenced twice, see change in 4 places.
if append value inner list:
ll[0][0][0][0].append(1)
you'd see value referenced 8 times:
[[[[[1], [1]], [[1], [1]]], [[[1], [1]], [[1], [1]]]]]
because inner lists same list.
the real structure of ll
isn't appears above, but:
[ ] | [ , ] \ / [ , ] \ / [ , ] \ / []
the way displayed python quite misleading.
Comments
Post a Comment