One of the most frequently used data structures in Python programming language is lists. They allow you to store collections of data in a mutable and ordered sequence. A powerful feature of Python lists is their ability to store more complex structures, such as a list of lists.
In Python, a list of lists is a list in which each element is itself a list. To create a list of lists in Python, simply include one or more lists as elements within another list. This concept is particularly useful for creating and handling multi-dimensional structures like matrices, nested loops, or organizing hierarchical data.
In this article, we’ll explore the details of a list of lists in Python. There will be examples provided to help you better understand the concepts.
Let’s get into it!
How to Create a List of Lists in Python
In Python, a list of lists, also known as a nested list, is a data structure that allows you to store multiple lists within a single list.
To create list of lists in Python, you can simply include one or more lists as elements in another list.
The following is an example of basic list of lists in Python:
list_of_lists = [['a', 'b'], ['c', 'd'], ['e', 'f']]
This list_of_lists contains three inner lists, each with two elements.
You can also create a list of lists with varying lengths or even empty sub-lists. The following is an example of a nested list with varying list lengths and empty sub-list:
list_of_lists = [[1, 2, 3], [4, 5], [], [6]]
The above is a basic way of creating a list of lists in Python, however, there are other more advanced ways as well. We’ll look at 2 more ways of creating a list of lists that you’ll find helpful when working with large-scale applications.
- Creating a list of lists with loops
- Creating a list of lists with list comprehension
1. How to Create a List of Lists With Loops
You can use loops to create a list of lists based on certain conditions or data.
For example, you might want to create a list containing n number of lists, each with m elements:
n = 3
m = 2
list_of_lists = [[0] * m for _ in range(n)]
This Python code block will create a list 3 by 2 empty list:
2. How to Create a List of Lists With List Comprehension
You can also create a list of lists using list comprehension. This is a compact and efficient way of generating lists in a single line of code.
In the following example, we create a list of lists with the squares of the numbers from 0 to 4 with list comprehension:
list_of_lists = [[i**2] for i in range(5)]
The output of the above code snippet will be:
Working With Lists of Lists: 8 Important Methods
Python lists are unique because they come with a range of methods that help you organize, manipulate, and retrieve data from lists.
In this section, we’ll look at some of the most common and frequently used methods when working with lists of lists in Python.
We’ll discuss the following:
- Accessing Elements
- Modifying Elements
- Iterating Through the Elements
- Adding Elements
- Removing Elements
- Flattening List of Lists
- Performing Matrix Operations
- Performing Slicing and indexing
1. How to Access Elements of List of Lists
Accessing elements in a list of lists requires two indices: one for the outer list and another for the inner list.
For example, to access the element at the second row and third column of the matrix above, you can use the following code:
matrix = [
[1, 2, 3],
[4, 5, 6],
[7, 8, 9]
]
value = matrix[1][2]
In the previous example, we told the interpreter to retrieve 3 elements from the second row. The index starts from 0 so [1] means “2” and [2] means “3”.
2. How to Modify Elements of List of Lists
Modifying elements in a list of lists works similarly to accessing them. You can use the assignment operator to update a specific element.
Let’s say we want to update the element 6 to 10 in the nested list. To achieve this, we can use the following code:
matrix = [
[1, 2, 3],
[4, 5, 6],
[7, 8, 9]
]
matrix[1][2] = 10
This will replace the value at the second row and third column with 10.
3. How to Iterate Through Elements of List of Lists
When iterating through the elements of a list of lists, you can use nested for loops.
The outer loop iterates through the rows, and the inner loop iterates through the columns.
In the example below, we iterate through each element of the list and print it to the console:
for row in matrix:
for element in row:
print(element, end=" ")
print()
The output will be:
4. How to Add an Element to a List of Lists
You can use the .append() method in Python to add an element to a list of list.
Let’s say we want to add a number to the second sub-list, the following is an example of adding an element to a nested list:
# matrix is defined as
matrix = [
[1, 2, 3],
[4, 5, 6],
[7, 8, 9]
]
# adding a number (e.g., 10) to the second sublist (index 1)
matrix[1].append(10)
print(matrix)
The output will be:
5. How to Remove an Element from a List of Lists
To remove an element from a List of Lists in Python, you can use the built-in remove() function in Python.
The following is an example of removing an element from a list of lists in Python:
matrix = [
[1, 2, 3],
[4, 5, 6, 10],
[7, 8, 9]
]
matrix[1].remove(10)
print(matrix)
This will remove element 10 from the list.
6. How to Flatten a Nested List
Flattening a list of lists in Python transforms it into a single list containing all of its elements.
To achieve this, you can use list comprehensions or the built-in sum() method with the second argument set to empty square brackets [].
The following example demonstrates flattening list of lists:
nested_list = [
[1, 2],
[3, 4],
[5, 6]
]
flattened_list = [item for sublist in nested_list for item in sublist]
This above example will convert the nested list into a flat list.
7. How to Perform Matrix Operations on List of Lists
A list of lists can represent a matrix, where the list elements are the rows, and the elements within each sub-list are the columns.
One important matrix operation is transposing a matrix. To transpose a matrix, elements at (i, j) need to swap places with elements at (j, i).
The zip() function can accomplish this with the help of * unpacking and list comprehensions.
The following example demonstrates transposing a matrix:
matrix = [
[1, 2, 3],
[4, 5, 6],
[7, 8, 9]
]
transposed_matrix = [list(row) for row in zip(*matrix)]
The output of the same list will be:
8. How to Perform Slicing and Indexing
Slicing and indexing allow you to retrieve and manipulate elements within a list of lists.
In Python, you can use the indexing syntax as a substitute for the list.get() function. You can access an item in the list by referring to its index number. Python list index starts from 0.
The following are examples of indexing in Python:
print(matrix[0]) # Prints the first sublist: [1, 2, 3]
print(matrix[1][2]) # Prints the third element from the second sublist: 6
The output of the above code snippet will be:
Slicing in Python is a feature that allows you to access parts of sequences like lists.
The following are examples of slicing list of lists:
print(matrix[1:]) # Prints everything from the second sublist onwards: [[4, 5, 6], [7, 8, 9]]
print(matrix[:2]) # Prints everything from the start to the third sublist: [[1, 2, 3], [4, 5, 6]]
The output will be:
2 Advanced Python List of Lists Techniques
In this section, we’ll explore some advanced Python tools and techniques for working with lists of lists.
We’ll focus on the following:
- Functional Programming
- Built-in Libraries
1. Functional Programming
Functional programming is a programming paradigm that treats computation as the evaluation of mathematical functions and avoids changing state and mutable data.
Python offers some techniques that can help you handle lists of lists using functional programming. The techniques are:
- Lambda Function
- Map Function
- Reduce Function
i. Performing Operations With Lambda Functions
Lambda functions are anonymous, single-expression functions that encourage concise syntax.
In the following example, we use a lambda function to extract the second element from each sublist in a list of lists.
matrix = [
[1, 2, 3],
[4, 5, 6],
[7, 8, 9]
]
extract_second_element = lambda x: x[1]
second_elements = list(map(extract_second_element, matrix))
print(second_elements)
The output will be:
ii. Performing Operations With the Map Function
The map() function applies a given function to each item in an iterable. You can use it with lists of lists to apply a lambda function to all the elements.
Let’s say we want to square each number in a list of lists. You can use the following code to achieve this:
# Define nested lists
matrix = [
[1, 2, 3],
[4, 5, 6],
[7, 8, 9]
]
# Define a function that squares every number in a list
def square_numbers(numbers):
return [x ** 2 for x in numbers]
# Use map to apply the function to every sublist in the matrix
squared_matrix = list(map(square_numbers, matrix))
print(squared_matrix)
The output will be:
iii. Performing Functions With the Reduce Function
The reduce() function allows you to apply a two-argument function cumulatively to the elements of a sequence, reducing it to a single value.
You can find the reduce() function in the functools module.
Let’s say we want to find the sum of the lengths of all sublists, you can use the following code:
from functools import reduce
list_of_lists = [['a', 'b'], ['c', 'd', 'e'], ['f']]
sum_of_lengths = reduce(lambda x, y: x + len(y), list_of_lists, 0)
The output will be:
2. Built-in Libraries
Python has several built-in libraries that can help you work with lists of lists efficiently.
In this section, we’ll discuss the following important functions that you should be familiar with:
- len() function
- .extend() function
- zip() function
i. len() Function
The len() function is commonly used to find the length of a list. The function returns the number of elements in a list:
main_list = [[1, 2], [3, 4, 5]]
lengths = [len(sublist) for sublist in main_list]
The output will be:
ii. .extend() Function
The .extend() function is commonly used to merge lists. This method appends the elements of one list to the end of another.
The following example demonstrates the use of .extend() function:
matrix1 = [[1, 2, 3], [4, 5, 6]]
matrix2 = [[7, 8, 9], [10, 11, 12]]
matrix1.extend(matrix2)
print(matrix1)
The output will be:
iii. zip() Function
The zip() function is used to combine two or more iterables element-wise.
To transpose a list of lists, you can use zip() combined with a list comprehension with the following code:
list_of_lists = [[1, 2, 3], [4, 5, 6], [7, 8, 9]]
transposed = [list(sublist) for sublist in zip(*list_of_lists)]
The output will be:
Learn some of the most important functions in Python by watching the following video:
Final Thoughts
Managing data is central to programming, and understanding how to manipulate complex data structures like a list of lists in Python is crucial. By mastering this concept, you give yourself a powerful tool to handle vast amounts of data efficiently. This can be especially important in areas like data science, machine learning, or game development, where data often comes in nested structures.
A list of lists allows you to structure your data in a meaningful, easy-to-understand way. It can represent things like a grid in a game, a table of data, or even the pixels in an image. Learning how to use this structure expands your possibilities as a programmer and enhances your problem-solving arsenal.
The more familiar you become with Python’s list of lists, the more you’ll appreciate its flexibility and power. Happy coding!
Frequently Asked Questions
How to create a nested list in Python?
A nested list, or list of lists, can be created in Python just like a regular list. To create a list of lists, you simply need to include lists as elements within a larger list.
Here’s a simple example:
nested_list = [[1, 2, 3], ['a', 'b', 'c'], [4.5, 6.7, 9.0]]
This creates a list containing three lists, each with different types of elements.
How to Access elements in a list of lists in Python?
To access elements in a nested list, use the indexing syntax with multiple indices. For instance, to access the element ‘b’ in the nested_list example:
element = nested_list[1][1]
The first index [1] refers to the second list, and the second index [1] refers to the second element in that list.
How to Iterate through a list of lists in Python?
There are multiple ways to iterate through a nested list. One common method is using nested for loops:
for sublist in nested_list:
for item in sublist:
print(item)
Another approach is using list comprehensions:
[item for sublist in nested_list for item in sublist]
How to check if an element is a list within a list in Python?
To determine if an element within a nested list is itself a list, you can use the isinstance() function:
for sublist in nested_list:
if isinstance(sublist, list):
print("This is a list:", sublist)
How to flatten a list of lists in Python?
To flatten a nested list, you can use a list comprehension with a nested for loop:
flattened_list = [item for sublist in nested_list for item in sublist]