pythonpython-2.7python-itertoolsfunction-composition

python "multiple" combine/chain list comprehension


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!


Solution

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