Python Initialize List of Lists (original) (raw)
Last Updated : 19 Dec, 2024
A **list of lists in Python is often used to represent multidimensional data such as rows and columns of a matrix. Initializing a list of lists can be done in several ways each suited to specific requirements such as fixed-size lists or dynamic lists. Let's explore the most efficient and commonly used methods.
**Using List Comprehension
List comprehension provides a concise and efficient way to create a list of lists, where each sublist is initialized as needed, avoiding the issue of shared references. It is Ideal for creating lists of fixed dimensions with initial values.
**Example:
Python `
Create a 3x3 matrix (list of lists) filled with 0s
a = [[0 for _ in range(3)] for _ in range(3)] print(a)
`
Output
[[0, 0, 0], [0, 0, 0], [0, 0, 0]]
Let's explore some other methods on how to initialize list of lists in Python
Table of Content
**Using Nested Loops
A nested loop allows manual creation of a list of lists offering flexibility to customize initialization. It is usually used when initialization requires more control over individual elements.
**Example:
Python `
a = []
Outer loop to create 2 sublists (rows)
for i in range(2):
Initialize an empty sublist for each row
sublist = []
# Inner loop to append 3 zeroes to each sublist
for j in range(3):
sublist.append(0)
# Append the sublist to the main list
a.append(sublist)
print(li)
`
Output
[[0, 0, 0], [0, 0, 0]]
Using Multiplication(*)
Multiplication(*) can be used to initialize a list of lists quickly but it creates sublists that share the same reference.
**Example:
Python `
a = [[0] * 3] * 3 print(a)
Modifying one sublist affects others
a[0][0] = 1 print(a)
`
Output
[[0, 0, 0], [0, 0, 0], [0, 0, 0]] [[1, 0, 0], [1, 0, 0], [1, 0, 0]]
**Using N umPy
Arrays
NumPy
library is efficient for initializing and manipulating lists of lists especially for numeric data. It used for performance critical applications involving numeric data.
**Example:
Python `
import numpy as np
#Create a 3x3 list of lists using numpy li = np.zeros((3, 3)).tolist() print(li)
`
Output
[[0.0, 0.0, 0.0], [0.0, 0.0, 0.0], [0.0, 0.0, 0.0]]
**Using Dynamic Initialization
Lists can be dynamically initialized by appending sublists during runtime. It is ideal to use when the size or content of the list is determined at runtime.
Example:
Python `
a = []
Outer loop to create 3 sublists (rows)
for i in range(3):
Append a sublist where the value of 'i'
a.append([i] * 3)
print(a)
`
Output
[[0, 0, 0], [1, 1, 1], [2, 2, 2]]