Python: Initialize A List Of Lists To A Certain Size,
Solution 1:
You can use list comprehension for example:
big_list = [[] for _ in range(200)]
That will create a list containing 200 different lists.
Solution 2:
You can multiply lists to achieve what you want to do:
big_list = [[]] * 200
Gives you a list of 200 empty lists. One caveat is that it will actually be 200 times the same list. This may not be what you want. For example appending to one of the lists will actually append to all, since they are all the same.
So for a list-of-lists, Paulo Bu's approach may be better. The multiplication feature is nice for constructing repeated strings or initializing a list of int's:
'A' * 5->'AAAAA'
[0] * 3-> [0, 0, 0]
The fact that the list contains different "names" for the same underlying object is not a problem here, it only becomes troublesome for mutable types, such as lists, dicts, sets, ... (but not the immutable tuples, for example)-
Post a Comment for "Python: Initialize A List Of Lists To A Certain Size,"