Python Initialize List of Lists
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
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 NumPy
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]]
Similar Reads
Flatten a List of Lists in Python Flattening a list of lists means turning a nested list structure into a single flat list. This can be useful when we need to process or analyze the data in a simpler format. In this article, we will explore various approaches to Flatten a list of Lists in Python.Using itertools.chain itertools modul
3 min read
Python | Convert list into list of lists Given a list of strings, write a Python program to convert each element of the given list into a sublist. Thus, converting the whole list into a list of lists. Examples: Input : ['alice', 'bob', 'cara'] Output : [['alice'], ['bob'], ['cara']] Input : [101, 202, 303, 404, 505] Output : [[101], [202],
5 min read
Python | Initializing multiple lists In real applications, we often have to work with multiple lists, and initialize them with empty lists hampers the readability of code. Hence a one-liner is required to perform this task in short so as to give a clear idea of the type and number of lists declared to be used. Method #1: Using loops We
4 min read
Convert List of Lists to Dictionary - Python We are given list of lists we need to convert it to python . For example we are given a list of lists a = [["a", 1], ["b", 2], ["c", 3]] we need to convert the list in dictionary so that the output becomes {'a': 1, 'b': 2, 'c': 3}. Using Dictionary ComprehensionUsing dictionary comprehension, we ite
3 min read
Python - Convert a list into tuple of lists When working with data structures in Python, there are times when we need to convert a list into a tuple of smaller lists.For example, given a list [1, 2, 3, 4, 5, 6], we may want to split it into a tuple of two lists like ([1, 2, 3], [4, 5, 6]). We will explore different methods to achieve this con
3 min read