简体   繁体   中英

Changing second-to-last entry in list changes all preceding entries

The code I'm trying to write includes for loops that fill in a list in reverse order: The last entry is set first, and then the t-th entry is set based on the (t+1)th entry, iterating backwards until it gets to the 0th entry. Unfortunately, I kept the getting the strange problem of all the entries before the 2nd-to-last being equal to the 2nd-to-last.

Strangely enough, I managed to reproduce the problem even without the for loop.

The entries in this example are lists of length 3 because that's how it is in my real work. The problem goes away if I just make the entries ints.

def bet(p):
    bet=[[0,0,0]]*p
    bet_end=[]
    for k in range(0,3):
        bet_end.append(1)
    bet[p-1]=bet_end
    for k in range(0,3):
        bet[p-2][k]=2
    return bet

test=bet(5)

I expect the output to be

[[0,0,0],[0,0,0],[0,0,0],[2,2,2],[1,1,1]]

Instead, I get

[[2,2,2],[2,2,2],[2,2,2],[2,2,2],[1,1,1]]

Why did the 0th, 1st and 2nd entries get affected by the change to the 3rd entry?

Change this line

bet=[[0,0,0]]*p

to,

bet=[[0,0,0] for i in range(p)]

Output:

>>> bet(5)
[[0, 0, 0], [0, 0, 0], [0, 0, 0], [2, 2, 2], [1, 1, 1]]

Why?

Read here to know how to initialize lists properly.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM