I'm relatively new to Python and learned, that function cannot return nothing, not even
None. In my application I want to iterate over a list and keep all non-
None results of a complicated function:
def complicated_function(x): if x < 0: return "a" elif x == 3.6: return "b" elif x == 4: return None # Idealy here nothing should be returned elif x > 10: return "c" else: return "d"
I have three soltuions and my question is which would you recommend me to use and are there better ones?
tmp = [complicated_function(x) for x in [-1, 2, 3.6, 4, 5, 20]] ret = [x for x in tmp if x]
ret = [complicated_function(x) for x in [-1, 2, 3.6, 4, 5, 20] if complicated_function(x)]
ret =  for x in [-1, 2, 3.6, 4, 5, 20]: tmp = complicated_function(x) if tmp: ret.append(tmp)
I think the first solution is slow, if the list to iterate over is very large. The second solution seems to be bad if the complated_function is really expensive (in rumtime). The third solution seems to be ok, but append is said to be significantly slower than list comprehension.