python - List of lists changes reflected across sublists unexpectedly -


i needed create list of lists in python, typed following:

mylist = [[1] * 4] * 3 

the list looked this:

[[1, 1, 1, 1], [1, 1, 1, 1], [1, 1, 1, 1]]   

then changed 1 of innermost values:

mylist[0][0] = 5 

now list looks this:

[[5, 1, 1, 1], [5, 1, 1, 1], [5, 1, 1, 1]]   

which not wanted or expected. can please explain what's going on, , how around it?

when write [x]*3 get, essentially, list [x, x, x]. is, list 3 references same x. when modify single x visible via 3 references it.

to fix it, need make sure create new list @ each position. 1 way is

[[1]*4 n in range(3)] 

the multiplication operator * operates on objects, without seeing expressions. when use * multiply [[1] * 4] 3, * sees 1-element list [[1] * 4] evaluates to, not [[1] * 4 expression text. * has no idea how make copies of element, no idea how reevaluate [[1] * 4], , no idea want copies, , in general, there might not way copy element.

the option * has make new references existing sublist instead of trying make new sublists. else inconsistent or require major redesigning of fundamental language design decisions.

in contrast, list comprehension reevaluates element expression on every iteration. [[1] * 4 n in range(3)] reevaluates [1] * 4 every time same reason [x**2 x in range(3)] reevaluates x**2 every time. every evaluation of [1] * 4 generates new list, list comprehension wanted.

incidentally, [1] * 4 doesn't copy elements of [1], doesn't matter, since integers immutable. can't 1.value = 2 , turn 1 2.


Comments

Popular posts from this blog

facebook - android ACTION_SEND to share with specific application only -

python - Creating a new virtualenv gives a permissions error -

javascript - cocos2d-js draw circle not instantly -