Why can't I change the list I'm iterating from when using yield

Viewed 55

I have some reproducible code here:

def test():
    a = [0, 1, 2, 3]
    for _ in range(len(a)):
        a.append(a.pop(0)) 
        for i in range(2,4):
            print(a)
            yield(i, a)

This prints out:

[1, 2, 3, 0]
[1, 2, 3, 0]
[2, 3, 0, 1]
[2, 3, 0, 1]
[3, 0, 1, 2]
[3, 0, 1, 2]
[0, 1, 2, 3]
[0, 1, 2, 3]

Which is what I expected, but when I do list(test()) I get:

[(2, [0, 1, 2, 3]),
 (3, [0, 1, 2, 3]),
 (2, [0, 1, 2, 3]),
 (3, [0, 1, 2, 3]),
 (2, [0, 1, 2, 3]),
 (3, [0, 1, 2, 3]),
 (2, [0, 1, 2, 3]),
 (3, [0, 1, 2, 3])]

Why is this the case, and what can I do to work around it?

4 Answers
Related