Initialise Python List to a Length with Default Values
To create a list in python 3 and fill it with default values, you can simply issue
>>> [False] * 5
[False, False, False, False, False]
This works fine for immutable objects, like a boolean or an int, but fails when
you use a mutable object like a dictionary, then you should use something
similar to (assuming {}
is your dictionary)
>>> [ {} for i in range(5) ]
[{}, {}, {}, {}, {}]
Otherwise you get a list with 5 times the same dictionary. Similarly, assuming you want a two dimensional matrix (5x5) and represent it as a list of lists with default values 0, then watch out with how you create it. To give an example of what can go wrong
>>> from pprint import pprint
>>> matrix = [ [0] * 5 ] * 5
>>> pprint(matrix)
[[0, 0, 0, 0, 0],
[0, 0, 0, 0, 0],
[0, 0, 0, 0, 0],
[0, 0, 0, 0, 0],
[0, 0, 0, 0, 0]]
>>> matrix[1][1]
0
>>> matrix[1][1] = 1
>>> pprint(matrix)
[[0, 1, 0, 0, 0],
[0, 1, 0, 0, 0],
[0, 1, 0, 0, 0],
[0, 1, 0, 0, 0],
[0, 1, 0, 0, 0]]
The problem starts with the outer * 5
since we are at that point multiplying
a list, a mutable object. So we get a list of 5 times our inner list and when
wanting to change one particular value in our matrix, we actually change that
one inner list, making it look like we changed the entire column! Instead use
the same tactic as earlier with the dictionary.
>>> from pprint import pprint
>>> matrix = [ ([0] * 5) for i in range(5) ]
>>> pprint(matrix)
[[0, 0, 0, 0, 0],
[0, 0, 0, 0, 0],
[0, 0, 0, 0, 0],
[0, 0, 0, 0, 0],
[0, 0, 0, 0, 0]]
>>> matrix[1][1] = 1
>>> pprint(matrix)
[[0, 0, 0, 0, 0],
[0, 1, 0, 0, 0],
[0, 0, 0, 0, 0],
[0, 0, 0, 0, 0],
[0, 0, 0, 0, 0]]