This post will discuss how to initialize the list of lists in Python.

To create a list of lists, never use [[]] * N. This will result in the list containing the same list object repeated N times and cause referencing errors. This post provides an overview of some of the available alternatives to create a list of lists the right way.

1. Using List Comprehensions

The most Pythonic solution for creating an empty list of lists is to use list comprehensions. This can be done as:

Download  Run Code

2. Using itertools

The itertools module has repeat() function that can replace range() function in the above list comprehension.

Download  Run Code

 
Note: Don’t directly call repeat([], n) as this will also result in the list containing the same list object repeated N times.

Download  Run Code

3. Using NumPy

This can be done using NumPy, but performance is often slower than the list comprehension.

That’s all about initializing a list of lists in Python.

 
Also See:

Initialize a list with the same values in Python