Var = [[0] * 5] * 5 Help understand python lists?

I came across a piece of division on a python list. I am a little confused in the behavior. Please explain this. I appreciate your help.

>>> v = [[0]*2]*2 >>> v [[0, 0], [0, 0]] >>> v[1][1] = 23 >>> v [[0, 23], [0, 23]] >>> v[1][1] = 44 >>> v [[0, 44], [0, 44]] >>> 
+4
source share
2 answers

The * operator for lists repeats their contents, as you can clearly see in the output.

However, it does not copy elements; it simply copies links to objects. Thus, in this case, both [0,0 ] have the same main list object, which should explain the phenomenon.

To check this, try v[0] = [0,44] to assign a new (and therefore independent!) List object to the first element of the main list; then try again to change v[1][1] . This time, the output will change only one record.

+7
source

v is just a list of lists.

* The first line of the line means "repeat 2 times 0 in my list." Thus, each list of nests is 2 in size and contains zeros.

Then you just set the values ​​for certain cells of the list of lists :)

0
source

Source: https://habr.com/ru/post/1394096/


All Articles