python – Double Iteration in List Comprehension

python – Double Iteration in List Comprehension

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!), (Whats, up?))
>>> [word for sentence in text for word in sentence]
[Hi, Steve!, Whats, up?]

This also works for generators

>>> text = ((Hi, Steve!), (Whats, up?))
>>> gen = (word for sentence in text for word in sentence)
>>> for word in gen: print(word)
Hi
Steve!
Whats
up?

To answer your question with your own suggestion:

>>> [x for b in a for x in b] # Works fine

While you asked for list comprehension answers, let me also point out the excellent itertools.chain():

>>> from itertools import chain
>>> list(chain.from_iterable(a))
>>> list(chain(*a)) # If youre using python < 2.6

python – Double Iteration in List Comprehension

Gee, I guess I found the anwser: I was not taking care enough about which loop is inner and which is outer. The list comprehension should be like:

[x for b in a for x in b]

to get the desired result, and yes, one current value can be the iterator for the next loop.

Leave a Reply

Your email address will not be published. Required fields are marked *