Initialize list of lists in Python
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:
1 2 3 4 5 6 |
if __name__ == '__main__': n = 10 a = [[] for x in range(n)] print(a) # [[], [], [], [], [], [], [], [], [], []] |
2. Using itertools
The itertools
module has repeat()
function that can replace range()
function in the above list comprehension.
1 2 3 4 5 6 7 8 |
from itertools import repeat if __name__ == '__main__': n = 10 a = [[] for x in repeat(None, n)] print(a) # [[], [], [], [], [], [], [], [], [], []] |
Note: Don’t directly call repeat([], n)
as this will also result in the list containing the same list object repeated N
times.
1 2 3 4 5 6 7 8 |
from itertools import repeat if __name__ == '__main__': n = 10 a = list(repeat([], n)) print(a) # [[], [], [], [], [], [], [], [], [], []] |
3. Using NumPy
This can be done using NumPy, but performance is often slower than the list comprehension.
1 2 3 4 5 6 |
import numpy n = 10 a = numpy.empty((n, 0)).tolist() print(a) # [[], [], [], [], [], [], [], [], [], []] |
That’s all about initializing a list of lists in Python.
Also See:
Thanks for reading.
To share your code in the comments, please use our online compiler that supports C, C++, Java, Python, JavaScript, C#, PHP, and many more popular programming languages.
Like us? Refer us to your friends and support our growth. Happy coding :)