python - Generating sublists using multiplication ( * ) unexpected behavior -


i'm sure has been answered somewhere wasn't sure how describe it.

let's want create list containing 3 empty lists, so:

lst = [[], [], []] 

i thought being clever doing this:

lst = [[]] * 3 

but discovered, after debugging weird behavior, caused append update 1 sublist, lst[0].append(3), update entire list, making [[3], [3], [3]] rather [[3], [], []].

however, if initialize list with

lst = [[] in range(3)] 

then doing lst[1].append(5)gives expected [[], [5], []]

my question why happen? interesting note if do

lst = [[]]*3 lst[0] = [5] lst[0].append(3) 

then 'linkage' of cell 0 broken , [[5,3],[],[]], lst[1].append(0) still causes [[5,3],[0],[0].

my best guess using multiplication in form [[]]*x causes python store reference single cell...?

my best guess using multiplication in form [[]] * x causes python store reference single cell...?

yes. , can test yourself

>>> lst = [[]] * 3 >>> print [id(x) x in lst] [11124864, 11124864, 11124864] 

this shows 3 references refer same object. , note really makes perfect sense happens1. copies values, , in case, values are references. , that's why see same reference repeated 3 times.

it interesting note if do

lst = [[]]*3 lst[0] = [5] lst[0].append(3) 

then 'linkage' of cell 0 broken , [[5,3],[],[]], lst[1].append(0) still causes [[5,3],[0],[0].

you changed reference occupies lst[0]; is, assigned new value lst[0]. didn't change value of other elements, still refer same object referred to. , lst[1] , lst[2] still refer same instance, of course appending item lst[1] causes lst[2] see change.

this classic mistake people make with pointers , references. here's simple analogy. have piece of paper. on it, write address of someone's house. take piece of paper, , photocopy twice end 3 pieces of paper same address written on them. now, take first piece of paper, scribble out address written on it, , write new address someone else's house. did address written on other 2 pieces of paper change? no. that's exactly code did, though. that's why other 2 items don't change. further, imagine owner of house address still on second piece of paper builds add-on garage house. ask you, house address on third piece of paper have add-on garage? yes, does, because it's exactly same house 1 address written on second piece of paper. explains everything second code example.

1: didn't expect python invoke "copy constructor" did you? puke.


Comments

Popular posts from this blog

php - Calling a template part from a post -

Firefox SVG shape not printing when it has stroke -

How to mention the localhost in android -