0
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 ?

5
  • 4
    state is the same list every time through the loop. Commented Jan 25, 2021 at 22:45
  • 5
    BTW, don't use list as a variable name, it shadows the built-in class/function. Commented Jan 25, 2021 at 22:46
  • 2
    Use final.append(state.copy()) Commented Jan 25, 2021 at 22:47
  • Ok I will try it Commented Jan 25, 2021 at 22:47
  • @PiotrekSzymański, you can make generator function and use next() which will be a bit more "pythonic". Commented Jan 25, 2021 at 22:52

1 Answer 1

2

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]]
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.