Initialize list 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]# [[], [], [], [], [], [], [], [], [], []]

DownloadRun Code

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]# [[], [], [], [], [], [], [], [], [], []]

DownloadRun Code


Note: Dont 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]# [[], [], [], [], [], [], [], [], [], []]

DownloadRun Code

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]# [[], [], [], [], [], [], [], [], [], []]

Thats all about initializing a list of lists in Python.


Also See:

Initialize a list with the same values in Python

Video liên quan

Chủ Đề