Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Double Iteration in List Comprehension

In Python you can have multiple iterators in a list comprehension, like

[(x,y) for x in a for y in b] 

for some suitable sequences a and b. I'm aware of the nested loop semantics of Python's list comprehensions.

My question is: Can one iterator in the comprehension refer to the other? In other words: Could I have something like this:

[x for x in a for a in b] 

where the current value of the outer loop is the iterator of the inner?

As an example, if I have a nested list:

a=[[1,2],[3,4]] 

what would the list comprehension expression be to achieve this result:

[1,2,3,4] 

?? (Please only list comprehension answers, since this is what I want to find out).

like image 440
ThomasH Avatar asked Jul 29 '09 08:07

ThomasH


People also ask

Are list comprehensions faster than for loops?

Because of differences in how Python implements for loops and list comprehension, list comprehensions are almost always faster than for loops when performing operations.


1 Answers

Suppose you have a text full of sentences and you want an array of words.

# Without list comprehension list_of_words = [] for sentence in text:     for word in sentence:        list_of_words.append(word) return list_of_words 

I like to think of list comprehension as stretching code horizontally.

Try breaking it up into:

# List Comprehension  [word for sentence in text for word in sentence] 

Example:

>>> text = (("Hi", "Steve!"), ("What's", "up?")) >>> [word for sentence in text for word in sentence] ['Hi', 'Steve!', "What's", 'up?'] 

This also works for generators

>>> text = (("Hi", "Steve!"), ("What's", "up?")) >>> gen = (word for sentence in text for word in sentence) >>> for word in gen: print(word) Hi Steve! What's up? 
like image 149
Skam Avatar answered Sep 29 '22 17:09

Skam