Pages

Dec 19, 2015

"[[0] * n] * m" is not equal to "[[0 for i in range(n)] for j in range(m)]"

# When generate list of list, be careful of following methods, they produce different results
>>> x = [[0] * 2] * 3
>>> x
[[0, 0], [0, 0], [0, 0]]
>>> y = [[0 for i in range(2)] for j in range(3)]
>>> y
[[0, 0], [0, 0], [0, 0]]
# although they look the same and are equal to each other
>>> x == y
True
# but... the operation can generate different results
>>> x[0][0] = 1
>>> x
[[1, 0], [1, 0], [1, 0]] # Surprise!! every list is changed
>>> y[0][0] = 1
>>> y
[[1, 0], [0, 0], [0, 0]] # this is what we expected
view raw List.py hosted with ❤ by GitHub