views:

696

answers:

2

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).

+1  A: 

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 :-). Sorry for the noise.

ThomasH
List comprehension syntax is not one of Python's shining points.
Glenn Maynard
@Glenn Yeah, it easily gets convoluted for more than simple expressions.
ThomasH
+7  A: 

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 you're using python < 2.6
Cide
@Cide Thanks for the pointer!
ThomasH
@Cide Initially, I wasn't getting it, but now I see: You meant to say list(chain(*a)), to be consistent with my example...
ThomasH
@ThomasH Correct you are. I've corrected it to use "a".
Cide
Just stumbled across this today and wanted to say that this is a great solution! Thanks for this.
jathanism