Search code examples
pythonlistempty-list

How can I make multiple empty lists in Python?


How can I make many empty lists without manually typing the following?

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

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


Solution

  • 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]]