![]() |
In this guide, we will explain the concept of Lists of Lists in Python, including various methods to create them and common operations that can be performed on Lists of Lists in Python. What is List of Lists in Python?A list of lists in Python is a list where each element of the outer list is itself a list. This creates a two-dimensional structure, often referred to as a matrix or a 2D list. Each inner list can have a different length, allowing for irregular or jagged structures. This versatile data structure is commonly used to represent tabular data, matrices, or nested collections of elements. Example: In this example, the matrix is a list of three lists, and each inner list represents a row of values. You can access individual elements using double indexing, such as matrix[0][1], to access the element in the first row and second column (which is 2 in this case). matrix = [
[1, 2, 3],
[4, 5, 6],
[7, 8, 9]
]
Create List of Lists in PythonThere, are various ways to create List of Lists in Python. here we are explaining some generally used method to List of Lists in Python and uses of List of Lists in Python those are following. Table of Content Create a List of Lists Using append() FunctionIn this example the code initializes an empty list called `list_of_lists` and appends three lists using append() function to it, forming a 2D list. The resulting structure is then printed using the `print` statement. Python
Output
[[1, 2, 3], [4, 5, 6], [7, 8, 9]] Create a List of Lists Using the List InitializerIn this example code employs a list initializer to create a 2D list named `list_of_lists`, representing rows of values. The resulting structure is printed using the `print` statement. Python
Output
[[1, 2, 3], [4, 5, 6], [7, 8, 9]] Create a List of Lists Using List ComprehensionIn this example, the inner list comprehension [i for i in range(1, 4)] generates a list [1, 2, 3]. The outer list comprehension [… for _ in range(3)] repeats this inner list three times, creating a list of lists with three rows. Python
Output
[[1, 2, 3], [1, 2, 3], [1, 2, 3]] Create a List of Lists Using For-Loop in PythonIn this example, the outer For-Loop iterates over the number of rows (rows), and for each iteration, an inner list is created using a list comprehension [j + 1 for j in range(columns)]. This inner list represents a row of values, and it’s appended to the list_of_lists. Python
Output
[[1, 2, 3], [1, 2, 3], [1, 2, 3]] Traverse a List of Lists in PythonIn this example code initializes a 3×3 list of lists called `list_of_lists`. It then uses nested loops to traverse through each element, printing them row-wise with a space-separated format. Python3
Output : 1 2 3
4 5 6
7 8 9
|
Reffered: https://www.geeksforgeeks.org
Python |
Type: | Geek |
Category: | Coding |
Sub Category: | Tutorial |
Uploaded by: | Admin |
Views: | 13 |