Simple python code about double loop

前端 未结 3 596
闹比i
闹比i 2021-01-20 16:04

I tested the following python code on Spyder IDE. Thinking it would output 2d array q as increasing number as 0..31 from q[0][0] to q[3][7]

3条回答
  •  [愿得一人]
    2021-01-20 16:12

    q=[somelist]*4 
    

    creates a list with four identical items, the list somelist. So, for example, q[0] and q[1] reference the same object.

    Thus, in the nested for loop q[i] is referencing the same list regardless of the value of i.

    To fix:

    q = [[0]*8 for _ in range(4)]
    

    The list comprehension evaluates [0]*8 4 distinct times, resulting in 4 distinct lists.


    Here is a quick demonstration of this pitfall:

    In [14]: q=[[0]*8]*4
    

    You might think you are updating only the first element in the second row:

    In [15]: q[1][0] = 100
    

    But you really end up altering the first element in every row:

    In [16]: q
    Out[16]: 
    [[100, 0, 0, 0, 0, 0, 0, 0],
     [100, 0, 0, 0, 0, 0, 0, 0],
     [100, 0, 0, 0, 0, 0, 0, 0],
     [100, 0, 0, 0, 0, 0, 0, 0]]
    

提交回复
热议问题