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]]
curr_locto the list every iteration. TrytotSteps.append(curr_loc[:])curr_locin the iteration, it prints out the updated value. I still don't understand why all previous values get replaced with the current value. Pythonappendmethod appends the value (or list) to the end of list.