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?
append() method adds an item to the end of the list. The method returns None as it mutates the original list. It is a convention in Python for methods that mutate the original object to return None . If you need to get a new list by appending a value to an existing list, use the addition (+) operator.
One of the best practices to do what you want to do is by using + operator. The + operator creates a new list and leaves the original list unchanged.
To append a value to a list if not already present: Use the not in operator to check if the value is not in the list. Use the list. append() method to append the value to the list if it's not already present.
append() doesn't return a list to use. . append() does its work in place. That means it actually modifies the object you call it on.
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]
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With