How to create a number of empty nested lists in python [duplicate]

Try a list comprehension:

lst = [[] for _ in xrange(a)]

See below:

>>> a = 3
>>> lst = [[] for _ in xrange(a)]
>>> lst
[[], [], []]
>>> a = 10
>>> lst = [[] for _ in xrange(a)]
>>> lst
[[], [], [], [], [], [], [], [], [], []]
>>> # This is to prove that each of the lists in lst is unique
>>> lst[0].append(1)
>>> lst
[[1], [], [], [], [], [], [], [], [], []]
>>>

Note however that the above is for Python 2.x. On Python 3.x., since xrange was removed, you will want this:

lst = [[] for _ in range(a)]

Leave a Comment