J P
J P

Reputation: 551

Python append removes elements from list

I have a function that appends a list to a list, but for some reason certain elements from that list get cleared...

Here is the function

def calculate_path(current_location, furthest):
    path = []
    directions = [[0, -1], [1, 1], [0, 1], [1, -1]]
    i = 0
    for direction in furthest:  # n e s w
        temp_location = copy.deepcopy(current_location)
        while temp_location != direction:
            temp_location[directions[i][0]] += directions[i][1]
            path.append(temp_location)
            print(path)
        i += 1
    return path

So given an input of current_location = [4, 4], furthest = [[1, 4], [4, 7], [5, 4], [4, 0]] the program gives this output:

[[3, 4]]
[[2, 4], [2, 4]]
[[1, 4], [1, 4], [1, 4]]
[[1, 4], [1, 4], [1, 4], [4, 5]]
[[1, 4], [1, 4], [1, 4], [4, 6], [4, 6]]
[[1, 4], [1, 4], [1, 4], [4, 7], [4, 7], [4, 7]]
[[1, 4], [1, 4], [1, 4], [4, 7], [4, 7], [4, 7], [5, 4]]
[[1, 4], [1, 4], [1, 4], [4, 7], [4, 7], [4, 7], [5, 4], [4, 3]]
[[1, 4], [1, 4], [1, 4], [4, 7], [4, 7], [4, 7], [5, 4], [4, 2], [4, 2]]
[[1, 4], [1, 4], [1, 4], [4, 7], [4, 7], [4, 7], [5, 4], [4, 1], [4, 1], [4, 1]]
[[1, 4], [1, 4], [1, 4], [4, 7], [4, 7], [4, 7], [5, 4], [4, 0], [4, 0], [4, 0], [4, 0]]

As you can see, it adds [3, 4] but then removes it? And the same for others? I realy can't work out why this might be happening...

Upvotes: 0

Views: 66

Answers (1)

AnsFourtyTwo
AnsFourtyTwo

Reputation: 2518

When you are inside the while loop you basically only work with the variable temp_location to append to the list path. For all iterations in that loop every element you append refers to the very same object.

So having 3 iterations in the while loop during one iteration of the outer for loop, will result in 3 elements being appended to your list, but with each element referring to the very same object.

You can avoid this by appending a copy of temp_location to the list:

path.append(temp_location.copy())

Upvotes: 1

Related Questions