Python list multiplication: [[...]]*3 makes 3 lists which mirror each other when modified [duplicate]
You've made 3 references to the same list.
>>> a = b = []>>> a.append(42)>>> b[42]
You want to do this:
P = [[()] * 3 for x in range(3)]
Lists are mutable, and multiplying a list by a number doesn't copy its elements. You can try changing it to a list comprehension, so it will evaluate [()]*3
three times, creating three different lists:
P = [ [()]*3 for i in range(3) ]
You can also write it like this, which has the advantage of showing the structure [[()]*3]*3
>>> P=[i[:] for i in [[()]*3]*3]>>> P[0][0]=1>>> P[[1, (), ()], [(), (), ()], [(), (), ()]
It's also slightly faster than using range. From ipython shell:
In [1]: timeit P = [ [()]*3 for i in range(3) ]1000000 loops, best of 3: 1.41 us per loopIn [2]: timeit P=[i[:] for i in [[()]*3]*3]1000000 loops, best of 3: 1.27 us per loop