Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Explanation of how nested list comprehension works?

Tags:

python

list

I have no problem understanding this:

a = [1,2,3,4] b = [x for x in a] 

I thought that was all, but then I found this snippet:

a = [[1,2],[3,4],[5,6]] b = [x for xs in a for x in xs] 

Which makes b = [1,2,3,4,5,6]. The problem is I'm having trouble understanding the syntax in [x for xs in a for x in xs], Could anyone explain how it works?

like image 435
Alvaro Fuentes Avatar asked Dec 17 '13 16:12

Alvaro Fuentes


People also ask

What is a nested list comprehension?

It is a smart and concise way of creating lists by iterating over an iterable object. Nested List Comprehensions are nothing but a list comprehension within another list comprehension which is quite similar to nested for loops.

How does nested list work in Python?

Lists are useful data structures commonly used in Python programming. A nested list is a list of lists, or any list that has another list as an element (a sublist). They can be helpful if you want to create a matrix or need to store a sublist along with other data types.

How do list comprehensions work?

List comprehensions provide us with a simple way to create a list based on some sequence or another list that we can loop over. In python terminology, anything that we can loop over is called iterable. At its most basic level, list comprehension is a syntactic construct for creating lists from existing lists.


1 Answers

Ah, the incomprehensible "nested" comprehensions. Loops unroll in the same order as in the comprehension.

[leaf for branch in tree for leaf in branch] 

It helps to think of it like this.

for branch in tree:     for leaf in branch:         yield leaf 

The PEP202 asserts this syntax with "the last index varying fastest" is "the Right One", notably without an explanation of why.

like image 79
wim Avatar answered Sep 30 '22 00:09

wim