简体   繁体   中英

Append list to a python list

I am trying to run a random walk on a two-dimensional grid with four equiprobable actions [right(1), left(-1), upward(1), downward(-1)]. As the random walker moves forward, I want to store its location (x, y coordinates) in the list totSteps . The x,y coordinates (that is, current location) will be updated on every step as a variable curr_loc . As you can see in the printed output, the first list ( curr_loc ) is the updated current location, and the second list ( totSteps ) supposedly contains the steps taken so far. There were 5 steps taken, and as such we have 10 outputs. Every time I append the curr_loc to totSteps ; all the previous coordinates get replaced with the current one. What's the reason?

steps = [1,-1,1,-1]
totSteps = [] # stores all the 5 steps taken but doesn't work 
# random walk with four steps left, right, 
# upward, downward on two dimensional grid
curr_loc = [0,0]
N = 5

for i in range(N):
    ranNums = np.random.randint(0,4) # picks one of four actions 
    if ranNums == 0 or ranNums == 1: # change x-coordinate
        curr_loc[0] += steps[ranNums] # taking the step 
        print(curr_loc) # current location of random walker 
        totSteps.append(curr_loc)
        print(totSteps) # append current location of random walker 
    elif ranNums == 2 or ranNums == 3: # chanfe y-coordinate 
        curr_loc[1] += steps[ranNums]
        print(curr_loc)
        totSteps.append(curr_loc) 
        print(totSteps)

The output of the code is given below:

>[1, 0] # curr_loc
>[[1, 0]] # totSteps
>[1, -1]
>[[1, -1], [1, -1]]
>[1, 0]
>[[1, 0], [1, 0], [1, 0]]
>[1, -1]
>[[1, -1], [1, -1], [1, -1], [1, -1]]
>[0, -1]
>[[0, -1], [0, -1], [0, -1], [0, -1], [0, -1]]

To further expand on @AndrejKesely's answer, you're not defining a new list object when a new loop iteration starts, and so whenever you change the values in curr_loc , since you're essentially appending another reference to curr_loc to totSteps , you have five references to the same object and that's why you're getting the same values.

Andrej's solution of curr_loc[:] means that you're effectively making a copy of the entire list and storing that rather than a reference to curr_loc .

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