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 ComprehensionsThe most Pythonic solution for creating an empty list of lists is to use list comprehensions. This can be done as:
DownloadRun Code 2. Using itertoolsThe itertools module has repeat() function that can replace range() function in the above list comprehension.
DownloadRun Code
DownloadRun Code 3. Using NumPyThis can be done using NumPy, but performance is often slower than the list comprehension.
Thats all about initializing a list of lists in Python.
|