Appending lists to lists as variables in for loops

a = []
b = [1,2,3]
from random import randrange
for i in range(100):
    if b not in a:
        a.append(b)
    b[randrange(0, 3)] += 1

My goal with this code is to set it so that every iteration of b is put into a. But this is not working, can anyone shed some light?

I thought that it would put every iteration into a. I thought that as b changed, the if loop would work as b was different and so therefore no longer what is in a.

1 Like

You’ve changed b, but b is the same (mutable) list as a[0], so you’re actually changing both of them. If you’d written a[0][randrange(0, 3)] += 1, you’d get the same result.

This is easy to fix, though, by copying the list. Change this line:

        a.append(b)

To:

        a.append(b.copy())

And it’ll work how you wanted it.

Thank you very much!