Search code examples
python-3.xlistlist-comprehensionpython-itertools

List comprehension flat list?


I have the following toy function:

def foo(a):
    return [a+5]

And I am running the following code:

my_lst = [foo(x) for x in range(10) if x%2 == 0]

Getting:

[[5], [7], [9], [11], [13]]

But need:

[5,7,9,11,13]

But I want to get a plain list, not a list of lists. How can I do it without itertools.chain.from_iterable(my_lst) but with list comprehension? What is the best practice? itertools or list comprehension in this case?

Please advice.

I have tried:

[j[0] for j in [foo(x) for x in range(10) if x%2 == 0]] 

Should I do it like this or there is a better way?


Solution

  • With list comprehension, it's done using two for loops:

    my_lst = [subx for x in range(10) if x%2 == 0 for subx in foo(x)]
    

    Also if you have a list of lists of one elements, you can "transpose" after the fact the list using zip:

    bad_lst = [foo(x) for x in range(10) if x%2 == 0]
    [my_lst] = zip(*bad_lst)
    

    Or you can "transpose" using a list comprehension combined with list unpacking as well if you truly want a list as output and not a tuple:

    bad_lst = [foo(x) for x in range(10) if x%2 == 0]
    my_lst = [x for [x] in bad_lst]