Python list confusion -


let's have following code:

a_list = [[0]*10]*10 

this generates following list:

[[0, 0, 0, 0, 0, 0, 0, 0, 0, 0],  [0, 0, 0, 0, 0, 0, 0, 0, 0, 0],  [0, 0, 0, 0, 0, 0, 0, 0, 0, 0],  [0, 0, 0, 0, 0, 0, 0, 0, 0, 0],  [0, 0, 0, 0, 0, 0, 0, 0, 0, 0],  [0, 0, 0, 0, 0, 0, 0, 0, 0, 0],  [0, 0, 0, 0, 0, 0, 0, 0, 0, 0],  [0, 0, 0, 0, 0, 0, 0, 0, 0, 0],  [0, 0, 0, 0, 0, 0, 0, 0, 0, 0],  [0, 0, 0, 0, 0, 0, 0, 0, 0, 0]] 

then want modify first element in first list:

a_list[0][0] = 23 

i expected first element of list modified, first element of each list changed:

[[23, 0, 0, 0, 0, 0, 0, 0, 0, 0],  [23, 0, 0, 0, 0, 0, 0, 0, 0, 0],  [23, 0, 0, 0, 0, 0, 0, 0, 0, 0],  [23, 0, 0, 0, 0, 0, 0, 0, 0, 0],  [23, 0, 0, 0, 0, 0, 0, 0, 0, 0],  [23, 0, 0, 0, 0, 0, 0, 0, 0, 0],  [23, 0, 0, 0, 0, 0, 0, 0, 0, 0],  [23, 0, 0, 0, 0, 0, 0, 0, 0, 0],  [23, 0, 0, 0, 0, 0, 0, 0, 0, 0],  [23, 0, 0, 0, 0, 0, 0, 0, 0, 0]] 

i managed find way represent data avoid why happening? why isn't first list changed? when second *10, python copy first list's address instead of allocating new memory block?

your hunch copying addresses correct. think this:

sub_list = [0] * 10 a_list = [sub_list] * 10 

this code equivalent code have posted above. means changing same list sub_list whenever change element of a_list. can make sure of typing:

a_list = [[0] * 10] * 10 n in a_list:     print id(n) 

and show same every element. remedy this, should use:

a_list = [[0] * 10 _ in range(10)] 

in order create new sublist every element of a_list.


Comments

Popular posts from this blog

c# - how to write client side events functions for the combobox items -

exception - Python, pyPdf OCR error: pyPdf.utils.PdfReadError: EOF marker not found -