Reputation: 2625
I got function that it's searching for something, and may not return anything. I want to append it to array but only if it return something
pseudocode
def fu():
if sometring:
return result
a = []
a.append(fu())
now if this function doesn't return value it appends "None" to array [result1, None, result2,etc]
, how to avoid that?
Upvotes: 8
Views: 15128
Reputation: 18027
A function automatically returns None
if you don't have a return statement. To avoid appending None
to a list, check it before appending.
result = f()
if result:
a.append(result)
Or use filter
to filter out None
in the end.
a = [1, 2, None, 3]
a = filter(None, a)
print(a)
# Output
[1, 2, 3]
Upvotes: 12