Python Initialize List of Lists
Last Updated :
09 Feb, 2024
Python, known for its simplicity and versatility, offers various ways to initialize a list of lists. This data structure is useful for representing a matrix, a 2D grid, or any other nested structure. In this article, we will explore five simple and commonly used methods to initialize a list of lists in Python.
Python Initialize List Of Lists
Below, are the methods for Python Initialize List Of Lists.
Python Initialize List Of Lists Using List Comprehension
List comprehension is a concise and powerful way to create lists in Python. To initialize a list of lists, you can use a nested list comprehension: below, code initializes a 3×4 matrix as a list of lists using list comprehension, setting all elements to 0. The resulting matrix is then printed.
Python3
rows, cols = 3 , 4
matrix = [[ 0 for _ in range (cols)] for _ in range (rows)]
print (matrix)
|
Output
[[0, 0, 0, 0], [0, 0, 0, 0], [0, 0, 0, 0]]
Python Initialize List Of Lists Using Nested Loops
A straightforward approach is to use nested loops to iterate through the desired number of rows and columns: Below, code initializes a 3×4 matrix as a list of lists using nested loops, setting all elements to 0. The resulting matrix is then printed.
Python3
rows, cols = 3 , 4
matrix = []
for _ in range (rows):
matrix.append([ 0 ] * cols)
print (matrix)
|
Output
[[0, 0, 0, 0], [0, 0, 0, 0], [0, 0, 0, 0]]
Python Initialize List Of Lists Using Replication with *
You can use the replication operator *
to replicate a list for the specified number of rows: This code initializes a 3×4 matrix as a list of lists by replicating a row template using the `*` operator and creating independent copies for each row with list slicing.
Python3
rows, cols = 3 , 4
row_template = [ 0 ] * cols
matrix = [row_template[:] for _ in range (rows)]
print (matrix)
|
Output
[[0, 0, 0, 0], [0, 0, 0, 0], [0, 0, 0, 0]]
Python Initialize List Of Lists Using the Numpy
Library
For more extensive numerical operations, you can use the numpy
library to initialize a list of lists. below, code initializes a 3×4 matrix as a list of lists using the `numpy` library, creating a matrix of zeros with the specified shape and data type, and then converting it to a standard Python list.
Python3
import numpy as np
rows, cols = 3 , 4
matrix = np.zeros((rows, cols), dtype = int ).tolist()
print (matrix)
|
Output :
[[0, 0, 0, 0], [0, 0, 0, 0], [0, 0, 0, 0]]
Conclusion
Initializing a list of lists in Python can be achieved through various methods, each with its own advantages. Whether you prefer the concise list comprehension or the explicit nested loops, understanding these approaches will empower you to work with nested structures efficiently in Python.
Share your thoughts in the comments
Please Login to comment...