Home > Mobile >  List comprehension flat list?
List comprehension flat list?

Time:09-14

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?

CodePudding user response:

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)

CodePudding user response:

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:

CodePudding user response:

Your function should return a number, not a list:

def foo(a):
    return a 5
  • Related