How can I make multiple empty lists in python?

Sameer Patel picture Sameer Patel · Nov 22, 2012 · Viewed 72.7k times · Source

How can I make many empty lists without manually typing

list1=[] , list2=[], list3=[]

Is there a for loop that will make me 'n' number of such empty lists?

Answer

Eric picture Eric · Nov 22, 2012

A list comprehension is easiest here:

>>> n = 5
>>> lists = [[] for _ in range(n)]
>>> lists
[[], [], [], [], []]

Be wary not to fall into the trap that is:

>>> lists = [[]] * 5
>>> lists
[[], [], [], [], []]
>>> lists[0].append(1)
>>> lists
[[1], [1], [1], [1], [1]]