Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Python3 append value to array but only if it's not None

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?

like image 609
Lord_JABA Avatar asked May 20 '16 16:05

Lord_JABA


People also ask

Why do I get none when I append in Python?

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.

How do I add an item to a list without adding an append?

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.

How do you append in list if not exist Python?

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.

Does append return anything?

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.


1 Answers

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]
like image 124
SparkAndShine Avatar answered Sep 30 '22 16:09

SparkAndShine