List comprehension flat list?

Viewed 33

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?

3 Answers

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]

alternatively to Laernes answer, you can also use itertools as :

list(itertools.chain(*[foo(x) for x in range(10) if x%2 == 0]))

or

list(itertools.chain.from_iterable([foo(x) for x in range(10) if x%2 == 0]))

More options here:

Your function should return a number, not a list:

def foo(a):
    return a+5
Related