This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
# 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 | |