Python list multiplication: [[...]]*3 makes 3 lists which mirror each other when modified

KFL picture KFL · Jul 14, 2011 · Viewed 23.7k times · Source

Why this is happening? I don't really understand:

>>> P = [ [()]*3 ]*3
>>> P
[[(), (), ()], [(), (), ()], [(), (), ()]]
>>> P[0][0]=1
>>> P
[[1, (), ()], [1, (), ()], [1, (), ()]]

Answer

Ignacio Vazquez-Abrams picture Ignacio Vazquez-Abrams · Jul 14, 2011

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)]