Reputation: 7056
I am quite new to python and I have been learning list comprehension alongside python lists and dictionaries.
So, I would like to do something like:
[my_functiona(x) for x in a]
..which works completely fine.
However, now I'd want to do the following:
[my_functiona(x) for x in a] && [my_functionb(x) for x in a]
..is there a way to combine or chain such list comprehension? - where the second function uses the result of the first list. SHortly speaking, I would like to apply my_functiona
and my_functionb
sequentuially to list a
I did try googling this - but could not find anything satisfactory. Sorry if this is a stupid 101 question!
Upvotes: 1
Views: 3674
Reputation: 304365
You can compose the functions like this
[my_functionb(my_functiona(x)) for x in a]
The form in Thomas' answer is useful if you need to apply a condition
[my_functionb(y) for y in (my_functiona(x) for x in a) if y<10]
Upvotes: 6
Reputation: 4392
You just iterate over the result of the first comprehension:
def double(x):
return x*2
def inc(x):
return x+1
[double(x) for x in (inc(y) for y in range(10))]
I made the inner comprehension a generator expression as you don't need to get the full list.
Upvotes: 6