Python list comprehension nested lists

Understanding nested list comprehension [duplicate]

I asked a similar question on Equivalent for loop expression for complex list comprehension
The answers given there reconstruct the form after understanding what it does internally.
I’d like to know how it works systematically so I can apply the concept to other slightly varying examples.

Side note: In your example, you could have transposed the rows into columns using cols = zip(*rows) , after which you could have simply used min(col) and max(col) for each column: [(min(c), max(c)) for c in cols] . Or in one short line: [(min(c), max(c)) for col in zip(*rows)] .

Would it be true, and improve clarity, if you were to write exp1(x,y) instead of just exp1 ? I think it’s implied, but would like to be sure?

«Here’s a detailed mental model; is my understanding correct?» generally doesn’t make a good question, because it’s mostly shoving the answer (or an attempt at one) into the question.

2 Answers 2

Indeed, you are correct. This is described in detail in the Expressions section in the Python Language Reference.

Note especially the order of nesting of several for s in a single list comprehension, which is always left-to-right:

>>> matrix = [[1, 2], [3, 4]] >>> [item for item in row for row in matrix] # oops! Traceback (most recent call last): File "", line 1, in [item for item in row for row in matrix] NameError: name 'row' is not defined >>> [item for row in matrix for item in row] # nesting is in left-to-right order [1, 2, 3, 4] 

I’ve looked at the link. Indeed, there’s an explanation for [item for row in matrix for item in row] but couldn’t find explanation for [[exp for item in row] for row in matrix] format. Am I missing something from the grammar listed there?

You’re not missing anything, but that’s because your example doesn’t use any more special grammar, it is just two simple list comprehensions! The first [exp for item in row] will create a list given a row. The «outer» list comprehension will create a list, in which each item is a list created by the «inner» list-comp, one for each row in the matrix.

Oh. As you pointed out in your answer, the order is important. And, I was wondering if there’s a section on library reference which talks about ordering of [[list comprehension] list comprehension] format.

There in no such section in the docs that I know of. The reason is that in a list comprehension, the expression evaluated for each item can be any valid Python expression. In this context, an «inner» list comprehension is just like any other Python expression.

Читайте также:  Jlist java что это

wow whee.. am I the only one surprised by this ordering: now an explanation why the macro level (matrix in this case..) occurs before the nested/micro level (row level..) might be in order..

The short answer is: yes, you are correct in your understanding.

There’s only a catch: the way you normally use nested list comprehension in python code is to operate on multidimensional arrays.

A typical example is when you operate on matrices:

>>> matrix = [[1, 2, 3], [4, 5, 6], [7, 8, 9]] >>> [[el - 1 for el in row] for row in matrix] [[0, 1, 2], [3, 4, 5], [6, 7, 8]] 

As you can see the «nesting» works by operating on each dimension of the matrix.

In the examples you provided, it seems that ySet [unfortunate name btw, as sets are one of the types provided with python] is just a generic counter, which makes a bit harder to follow what is going on under the hood.

As for your first example:

>>> rows = ([1, 2, 3], [10, 20, 30]) >>> [(min([row[i] for row in rows]),max([row[i] for row in rows])) for i in range(len(rows[0]))] [(1, 10), (2, 20), (3, 30)] 

You might wish to look into the zip built-in function:

>>> zip(rows[0], rows[1]) [(1, 10), (2, 20), (3, 30)] 

or for maximum brevity and elegance:

Источник

Nested List Comprehensions in Python

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.

Читайте также:  Java datetime mysql datetime

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 lists matrix = [[0,1,2],[0,1,2],[0,1,2]] print(matrix) 

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) 

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)

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) 

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

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

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) 

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) 

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.

Читайте также:  Meta content text html charset unicode

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) 

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) 

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 Flatland flat = [x for row in matrix for x in row] print(flat) 

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) 

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.

Источник

Оцените статью