0

The way it is I can only call funct() once per iteration. So I can't do this:

result=[funct(arg) for arg in args if arg and funct(arg)] 

If there is a connection drop this function returns None. If None is returned I don't want to add it to the resulted list. How to achieve it?

def funct(arg):
    if arg%2: return arg*2

args=[1,2,3,None,4,5]

result=[funct(arg) for arg in args if arg] 
print result
alphanumeric
  • 17,967
  • 64
  • 244
  • 392
  • possible duplicate of [Python list comprehension: test function return](http://stackoverflow.com/questions/13632280/python-list-comprehension-test-function-return) – ashwinjv Aug 26 '14 at 00:23

2 Answers2

2

You can use filter as you will not be returning any 0 values to your list:

result = filter(None,map(funct,filter(None,args)))

It will filter your args list and any None values returned

On a list with 20 elements args:

In [18]: %%timeit                   

[val for arg in args
              if arg                 
              for val in [funct(arg)]
              if val is not None]
   ....: 
100000 loops, best of 3: 10.6 µs per loop

In [19]: timeit filter(None,map(funct,filter(None,args)))
100000 loops, best of 3: 6.42 µs per loop

In [20]: timeit [a for a in [funct(arg) for arg in args if arg] if a]

100000 loops, best of 3: 7.98 µs per loop
Padraic Cunningham
  • 176,452
  • 29
  • 245
  • 321
1

you can nest comprehensions

result=[a for a in [funct(arg) for arg in args if arg] if a]
user2085282
  • 1,077
  • 1
  • 8
  • 16