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

javascript - gulp-nodemon - nodejs restart after file change - Error: listen EADDRINUSE events.js:85 -

Fatal Python error: Py_Initialize: unable to load the file system codec. ImportError: No module named 'encodings' -

javascript - oscilloscope of speaker input stops rendering after a few seconds -