2

The code below result to list of lists: [[1, 2, 3], [4, 5, 6]] How to modify it so the result is a simple list:`[1,2,3,4,5,6]?

def functA():
    return [1,2,3]
def functB():
    return [4,5,6]
def functC():
    return None

functs=[functA, functB, functC]

result=[a for a in [funct() for funct in functs] if a]

print result
alphanumeric
  • 17,967
  • 64
  • 244
  • 392
  • 2
    have a look at list.extend – user2085282 Aug 26 '14 at 01:06
  • I would like to achieve this while being inside of list comprehension. – alphanumeric Aug 26 '14 at 01:08
  • All of the answers that were given directly here are bad, because one of the most common/standard ways to solve the problem is by using a list comprehension in the right way, and the code **is already using** a list comprehension to gather results from the functions. All we need to do is rearrange it: `[a for a in [funct() for funct in functs] if a]` -> `[a for funct in functs if funct() for a in funct()]`. Rather than doing the filtering, it would be better to just return `[]` rather than `None` - as they say, "special cases aren't special enough to break the rules". – Karl Knechtel Sep 06 '22 at 02:13

4 Answers4

6

Use the itertools.chain method:

For instance, this code:

from itertools import chain
print list(chain.from_iterable([[1, 2, 3], [4, 5, 6]]))

Will print out:

[1, 2, 3, 4, 5, 6]

In your case, you can use:

result = list(chain.from_iterable(a for a in [funct() for funct in functs] if a))

result will then be:

[1, 2, 3, 4, 5, 6]
therealrootuser
  • 10,215
  • 7
  • 31
  • 46
1

I would recommend using chain from itertools

However your function should return an empty list instead of None since this is friendlier with the expected format.

Since the first list of lists is temporary I made it a generator sequence.

from itertools import chain

def functA():
    return [1,2,3]

def functB():
    return [4,5,6]

def functC():
    return [] # returns an empty list, in line with what is expected.

functs=[functA, functB, functC]

result = list(chain(*(a() for a in functs)))

print result
Serdalis
  • 10,296
  • 2
  • 38
  • 58
0

If you really want to use a list comprehension, try this one:

result= [item
         for sublist in [funct()
                         for funct in functs]
         if sublist is not None
         for item in sublist]
Robᵩ
  • 163,533
  • 20
  • 239
  • 308
0

You can flatten using a list comp also:

result=[ x for y in (a for a in (funct() for funct in functs) if a) for x in y]
Padraic Cunningham
  • 176,452
  • 29
  • 245
  • 321