List of Lists in Python
Lists are a fundamental data structure in Python, offering a versatile way to organize and manipulate data. When it comes to dealing with more complex structures, a list of lists becomes a powerful tool.
In this tutorial, you will learn about lists of lists in Python, including how to create them, access them, and manipulate them. You will also learn how to iterate over lists of lists, and how to use them to store more complex data.
- Understanding List of Lists
- Creating a List of Lists
- Accessing and Modifying Elements
- Iterating Through a List of Lists
- Adding and Removing Elements
- Flattening a Nested List
- Best Practices and Tips
- Conclusion
Table of Contents
1. Understanding List of Lists
Before we dive into the details of lists of lists, let's first understand what they are and why they are useful.
A list of lists, also known as a nested list, is essentially a list where each element is itself a list. This structure allows for the representation of two-dimensional data, such as matrices or tables.
You can see in the above image that each cell in original list is itself a list. This is the basic idea behind a list of lists.
2. Creating a List of Lists
A list of list can be created in multiple ways. Let's explore each of them.
2.1. Using the append() Function
The append() method adds an element at the end of the list. If the element is itself a list, it will be added as a single element.
# Creating a list of lists using append()
matrix = []
# π appending 3 lists to matrix
matrix.append([1, 2, 3])
matrix.append([4, 5, 6])
matrix.append([7, 8, 9])
print(matrix)
Output:
[[1, 2, 3], [4, 5, 6], [7, 8, 9]]
2.2. List Initializer Approach
You can directly initialise a list of list using folllowing approach.
# π List initializer approach
matrix = [[1, 2, 3], [4, 5, 6], [7, 8, 9]]
2.3. List Comprehension Magic
Another way to create a list of lists is to use list comprehension.
# π List comprehension approach
matrix = [[i for i in range(1, 4)] for j in range(3)]
The above code creates a list of list with 3 rows and 3 columns.
2.4. For-loop Method
Finally, you can also use python for-loop to create a list of lists.
# π For-loop approach
matrix = []
for i in range(3):
row = []
for j in range(3):
row.append(j)
3. Accessing and Modifying Elements
List of lists or matrix use 2 indicies to locate the element. The first index is used to locate the row and the second index is used to locate the column.
For example, to access the element at row 2 and column 3, you can use matrix[1][2]
.
matrix = [[1, 2, 3], [4, 5, 6], [7, 8, 9]]
# π Accessing elements
print(matrix[1][2]) # 6
Similarly, to modify the element access it using the above syntax and assign it a new value.
matrix = [[1, 2, 3], [4, 5, 6], [7, 8, 9]]
# π Modifying elements
matrix[1][2] = 10
print(matrix[1][2]) # 10
4. Iterating Through a List of Lists
To interate through a list of lists, you have to use nested for-loops.
First for-loop will iterate through the rows and the second for-loop will iterate through the columns.
matrix = [[1, 2, 3], [4, 5, 6], [7, 8, 9]]
# π Iterating through a list of lists
for row in matrix:
for col in row:
print(col, end=" ")
print() # new line
The above code will print the following output.
1 2 3 4 5 6 7 8 9
5. Adding and Removing Elements
Adding and removing elements is an important part of working with list or matrix. Let's see how to add and remove elements from a list of lists.
5.1. Adding an Element
To add an element to a list of lists, you can use following methods.
- append(item) Method: It adds the passed item at the end of the list.
- insert(index, item) Method: It inserts the passed item at the specified index.
- extend(iterable) Method: It extends the list by appending elements from the iterable.
# Adding an element
matrix = []
# π append() method
matrix.append([1, 2, 3])
print(matrix) # [[1, 2, 3]]
# π insert() method
# add [4, 5, 6] at index 0
matrix.insert(0, [4, 5, 6])
print(matrix) # [[4, 5, 6], [1, 2, 3]]
# π extend() method
# add 'a', 'b', 'c' at the end of the list
matrix.extend("abc")
print(matrix) # [[4, 5, 6], [1, 2, 3], 'a', 'b', 'c']
5.2. Removing an Element
To remove an element from a list of lists you can use pop() method. It accepts an index as an argument and removes the element at that index. By default, it removes the last element from the list.
matrix = [[1, 2, 3], [4, 5, 6], [7, 8, 9]]
# π Removing an element
# remove the last element
matrix.pop()
print(matrix)
# remove the element at index 0
matrix.pop(0)
print(matrix)
Output:
[[1, 2, 3], [4, 5, 6]] [[4, 5, 6]]
6. Flattening a Nested List
Flattening a nested list means converting a list of lists into a single list. For example, [[1, 2, 3], [4, 5, 6]] will be converted to [1, 2, 3, 4, 5, 6].
The following example is using list comprehension to flatten a nested list into a single list.
matrix = [[1, 2, 3], [4, 5, 6], [7, 8, 9]]
# π Flattening a nested list
flat_list = [item for row in matrix for item in row]
print(flat_list)
Output:
[1, 2, 3, 4, 5, 6, 7, 8, 9]
7. Best Practices and Tips
Here are some best practices and tips that you should keep in mind while working with lists of lists.
- Ensure consistency in the length of sublists, otherwise you will get IndexError.
- Consider using NumPy for large-scale matrix operation.
- Be mindful of double indexing while accessing elements.
Conclusion
Mastering the use of lists of lists in Python opens up possibilities for handling two-dimensional data structures efficiently.
By understanding the creation, manipulation, and advanced techniques presented in this guide, you can confidently incorporate lists of lists into your Python projects.
Happy coding!π