Q:Pythonic way to create list of lists
Arnaud Delobelle
arnodel at googlemail.com
Sun Apr 12 07:01:44 EDT 2009
grkuntzmd at gmail.com writes:
> I am just learning Python.
>
> I am trying to create a list of empty lists: [[], [], [], ...] (10
> items total).
>
> What is the most Pythonic way to do this?
>
> If I use a list comprehension (as in myList = [[] for item in xrange
> (0, 10)]), Netbeans warns me that 'item' is never used.
IMHO this is the best way.
> If I use a for-loop (as in for item in myList = []; for item in xrange
> (0, 10): myList.append([])), Netbeans still warns me of the same
> thing.
>
> If I use '*' (as myList = [[]] * 10), all of the empty lists refer to
> the same object; changing one changes them all.
>
> Do I have to live with the warning, or is there a "better" way?
You could do this:
>>> map(list, [()]*10)
[[], [], [], [], [], [], [], [], [], []]
But it is wasteful as it creates two lists.
There are some contrived ways to go around this using using itertools,
e.g.
>>> from itertools import *
>>> map(list, repeat((), 10))
[[], [], [], [], [], [], [], [], [], []]
Note that if you use Python 3 you would get an iterator so it would need
to be wrapped in a list() call. Or you could take advantage of
iter(function, sentinel) which is little used:
>>> list(islice(iter(list, None), 10))
[[], [], [], [], [], [], [], [], [], []]
But none of these are very compelling.
--
Arnaud
More information about the Python-list
mailing list