Last modified: Oct 28, 2024 By Alexander Williams
Python List of Lists: A Complete Guide
A list of lists in Python is a versatile structure, allowing you to store multiple lists as elements within a single list. This nested format is great for organizing complex data.
What is a List of Lists?
A list of lists is simply a Python list where each element itself is a list. This setup is perfect for working with tables or matrices.
matrix = [[1, 2, 3], [4, 5, 6], [7, 8, 9]]
In this example, matrix
contains three lists, each representing a row of a 3x3 grid.
Creating a List of Lists
You can create a list of lists by placing multiple lists inside a single set of square brackets []
.
nested_list = [["apple", "banana"], ["cherry", "date"], ["fig", "grape"]]
This structure is especially useful for organizing data with categories and subcategories. See Creating Lists in Python: A Beginner's Guide for more list basics.
Accessing Elements in a List of Lists
To access elements, specify the index of the outer list followed by the inner list’s index.
second_item = nested_list[0][1]
This retrieves "banana" from the first list. This indexing method makes it easy to locate specific elements.
Iterating Through a List of Lists
Use a nested for
loop to access each item within sublists.
for sublist in nested_list:
for item in sublist:
print(item)
This loop will print each item in the nested_list
, making it easier to process or display all elements.
Modifying a List of Lists
Python lists are mutable, so you can change elements directly by accessing them through indexing.
nested_list[1][1] = "dragonfruit"
Now, "date" is replaced with "dragonfruit". Modifying elements is straightforward when managing nested lists.
Adding and Removing Lists
Use append()
to add a new list to the main list, and remove()
to delete it.
nested_list.append(["kiwi", "lemon"])
nested_list.remove(["cherry", "dragonfruit"])
This code adds and removes lists, modifying the nested structure efficiently.
Using List Comprehension with a List of Lists
List comprehension works with nested lists to perform operations on each element. For example, squaring each number in a matrix:
squared_matrix = [[x**2 for x in row] for row in matrix]
This creates a new matrix where each element is squared. List comprehension is a powerful tool for concise code.
Conclusion
A list of lists is an effective way to organize complex data in Python, ideal for beginners and advanced programmers alike.
Explore more about lists in the Python documentation and learn list conversion techniques in Python List to String with Commas Examples.