Nested List Comprehensions in Python - PythonForBeginners.com (2024)

One way Python attracts programmers is by encouraging elegant, easy-to-read code. It does this through a variety of features, including list comprehension.

Writing more efficient code helps programmers save time and effort. List comprehension in Python achieves this goal by simplifying the syntax necessary to perform complex statements in Python.

Nested list comprehension takes this process further, allowing Python to create a list of lists in a single line of code. This is a powerful and flexible feature often used to generate matrices.

Why use List Comprehension?

List comprehension is an attractive feature because it can save programmers time and energy. Simplifying syntax means coders can complete complex operations with less code.

And because list comprehension statements are simplified, they are generally easier to read.

The advantages of using list comprehension include:

  • Generally easier to read and maintain
  • Takes less code to write
  • Powerful and flexible functionality
  • Better performance than for loops

Using list comprehension won’t make things easier in every case, however. That’s why we’re going to take a deep dive into some examples of when and how to use this popular Python feature.

How to use Nested List Comprehension

List comprehension in Python uses the for and in keywords. These keywords tell Python we want to loop over an iterable and do something with the results. To complete the list comprehension, we need our statement inside a set of square brackets.

Basic List Comprehension Syntax:

new_list = [expression for item in list]

Expression: The expression is used to modify each item in the statement.
Item: The element in the iterable
List: An iterable object.

Nested List Comprehension Syntax:

new_list = [[expression for item in list] for item in list]

Iterables

Using the range() function to generate an iterable is a common technique in Python. An iterable is a Python object that can be iterated over, such as a list.

We’ll use range() to construct for loops we can use to build matrices.

Building a Matrix in Python

We can build a matrix in Python using nested square brackets. In this example, you can see that we’re creating a list of lists. By wrapping three different lists inside another list, we can construct a Python list of lists.

Example 1: A basic Python matrix

# create a list of listsmatrix = [[0,1,2],[0,1,2],[0,1,2]]print(matrix)

Output

[[0, 1, 2], [0, 1, 2], [0, 1, 2]]

Alternatively, a matrix can be created with a pair of nested for loops and the append() method.

Example 2: Using for loops to create a matrix

matrix = []for y in range(3): matrix.append([]) for x in range(3): matrix[y].append(x)print(matrix)

Output

[[0, 1, 2], [0, 1, 2], [0, 1, 2]]

Finally, we’ll create a matrix using Python list comprehension. The list comprehension statement uses nested brackets, the range() function, and the keywords for and in to construct the statement.

matrix = [[x for x in range(3)] for y in range(3)]print(matrix)

Output

[[0, 1, 2], [0, 1, 2], [0, 1, 2]]

As you can see, the list comprehension statement takes up less space than the double for loop method of constructing a matrix.

In each example, the output was the same. Each technique can be used to create the same Python list of lists.

However, with the nested list approach we only needed a single line of code to achieve the desired results. And the method we used was just as flexible as a nested loop, which can be cumbersome to read and write.

Examples of Using List Comprehension

Let’s use list comprehension to create a Tic-Tac-Toe board. Most people are familiar with Tic-Tac-Toe. But in case you’ve been living under a rock, it’s a simple game of territory.

A basic Tic-Tac-Toe board is a 3×3 grid of squares. We can create the game board with list comprehension, filling each square with an empty space.

Example 3: Building a Tic-Tac-Toe board

tic_tac_toe_board = [[' ' for x in range(3)] for y in range(3)]def PrintMatrix(matrix): for row in range(len(matrix)): print(matrix[row])PrintMatrix(tic_tac_toe_board)

Output

[' ', ' ', ' '][' ', ' ', ' '][' ', ' ', ' ']

We can place an ‘X’ on the gameboard using list notation.

tic_tac_toe_board[1][1] = 'X'PrintMatrix(tic_tac_toe_board)

Output

[' ', ' ', ' '][' ', 'X', ' '][' ', ' ', ' ']

Creating a Matrix from a Series

It’s possible to turn a series of numbers into a matrix using list comprehension. By manipulating the expression part of the list comprehension statement, each item in the generated matrix will be modified.

We’ll have the matrix store a range of numbers 0-8, separated evenly into three rows.

Example 4: Using expressions

matrix = [[x+(y*3) for x in range(3)] for y in range(3)]print(matrix)

Output

[[0, 1, 2], [3, 4, 5], [6, 7, 8]]

Transposing Nested Lists

We can use Python list comprehension to transpose a matrix. To transpose a matrix, we need to turn each row into a column.

Example 5: Transposing a matrix

matrix = [[1,2,3], [4,5,6], [7,8,9]]transposed = [[x[y] for x in matrix] for y in range(len(matrix))]print(transposed)

Output

[1, 4, 7][2, 5, 8][3, 6, 9]

Filtering Nested List Comprehension Statements

We can provide a condition to the list comprehension that will act as a filter on the results. Only those items that meet the criteria of the condition will be accepted.

Conditions: Selects elements that meet the criteria of the condition.

Using conditions, we can tell Python we’re only interested in specific elements in the list. Which elements are selected will depend on the conditions provided.

For example, we can provide the list comprehension with a condition that selects only even numbers.

Example 6: Filtering a matrix for even numbers

matrix = [x for x in range(1,10) if x%2 == 0]print(matrix)

Output

[2, 4, 6, 8]]

Additionally, by nesting the list comprehension, we can create a matrix of even numbers.

matrix = [[x for x in range(1,10) if x%2 == 0] for y in range(2)]print(matrix)

Output

[[2, 4, 6, 8], [2, 4, 6, 8]]

Flattening a Nested List

Perhaps we need to flatten a matrix into a single list. This is sometimes necessary in computer graphics and image processing.

We can do this in Python using list comprehension. By adjusting the expression in the statement, we can tell Python to flatten the original, multi-dimensional list.

Example 7: Going from two dimensions to one

matrix = [[1,2,3], [4,5,6], [7,8,9]]# welcome to Flatlandflat = [x for row in matrix for x in row]print(flat)

Output

[1, 2, 3, 4, 5, 6, 7, 8, 9]

Let’s take a closer look at that statement: flat = [x for row in matrix for x in row]. Pretty confusing, right? While this statement serves as a more efficient way of flattening a matrix than a for loop, this is one case where list comprehension might be more difficult to understand than its counterpart.

Here’s how to flatten a list of lists using a for loop and the append() method.

Example 8: Flatten a list of lists

list = []for row in matrix: for x in row: list.append(x)print(list)

Output

[1, 2, 3, 4, 5, 6, 7, 8, 9]

Deciding when to use list comprehension is up to you as a programmer. Style and technique are often subjective. What’s important is that you make a conscious effort to improve your code and make it easier to understand.

Tips for Writing List Comprehension Statements in Python

Python provides list comprehension as a means of creating concise, easy-to-read code. To that end, we’ve included a short list of tips for working with list comprehension in Python.

  • List comprehension is more efficient than using standard for loops.
  • In the name of elegant code, we should keep list comprehensions statements short.
  • Use conditions to add flexibility to a list comprehension expression.
  • List comprehension is perfect for creating matrices.

There’s no set rule on when to use list comprehension. You should view it as another tool in your Python toolbox that can save you time and effort. Learning when to use list comprehension to improve your code will become more obvious as you improve.

Conclusion

List comprehension is a distinctive feature of Python that helps coders write elegant and easy-to-understand programs. Using list comprehension not only saves lines of code, but it can often be easier to read than alternative methods.

While list comprehension is generally considered more “Pythonic” than other methods, such as for loops, this isn’t necessarily true. Python code is designed for flexibility and efficiency. Every tool in Python has its strengths and weaknesses.

In order to get the most out of Python list comprehension, we can add a condition to filter the results. Using filters adds flexibility to list comprehensions expressions.

If you’re eager to learn more Python, and we hope you are, here are some additional links that will help you on your way to becoming a programming aficionado.

Related Posts

  • Learn how to craft better strings using Python string concatenation.
  • How to use Python split() to split strings into words.

Related

Recommended Python Training

Course: Python 3 For Beginners

Over 15 hours of video content with guided instruction for beginners. Learn how to create real world applications and master the basics.

Enroll Now

Nested List Comprehensions in Python - PythonForBeginners.com (2024)
Top Articles
Latest Posts
Article information

Author: Foster Heidenreich CPA

Last Updated:

Views: 6191

Rating: 4.6 / 5 (76 voted)

Reviews: 83% of readers found this page helpful

Author information

Name: Foster Heidenreich CPA

Birthday: 1995-01-14

Address: 55021 Usha Garden, North Larisa, DE 19209

Phone: +6812240846623

Job: Corporate Healthcare Strategist

Hobby: Singing, Listening to music, Rafting, LARPing, Gardening, Quilting, Rappelling

Introduction: My name is Foster Heidenreich CPA, I am a delightful, quaint, glorious, quaint, faithful, enchanting, fine person who loves writing and wants to share my knowledge and understanding with you.