Piotrek Szymański
Piotrek Szymański

Reputation: 43

why doesn't append in python work properly?

def get_next_state_for_x(list, next_state):
    final = []
    state = list
    for g in range (len(next_state)):
        temp = state[g]
        state[g] = next_state[g]
        print(state)
        final.append(state)
        state[g] = int(temp)
    print(final)
get_next_state_for_x([0, 0, 0, 0], [1, 1, 1, 1])

so while i compile this code i get the output:

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

instead of (for the last line)

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

why does final.append(state) add wrong list to the result ?

Upvotes: 0

Views: 52

Answers (1)

FrancecoMartino
FrancecoMartino

Reputation: 419

You're linking the list, so it changes everytime. You have to copy it

Correct to:

final.append(state.copy())

So:

def get_next_state_for_x(list, next_state):
    final = []
    state = list
    for g in range (len(next_state)):
        temp = state[g]
        state[g] = next_state[g]
        print(state)
        final.append(state.copy())
        state[g] = int(temp)
    print(final)
get_next_state_for_x([0, 0, 0, 0], [1, 1, 1, 1])

Output:

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

Upvotes: 2

Related Questions