Python: Initialize a list of lists to a certain si

2019-02-28 00:19发布

问题:

I'm trying to initialize 'big_list', which is a list containing lists, and we know in advance that there will be 200 lists within 'big_list', and that each list will contain only strings or nothing, and that later in the program there will be a loop that appends(one or more times) to only a certain number of those lists.

Is there a simplest way to go about this?

回答1:

You can use list comprehension for example:

big_list = [[] for _ in range(200)]

That will create a list containing 200 different lists.



回答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)-