With Python you have multiple options to remove
None values from a list. Those options include a basic for loop or by using list comprehension.
A more readable option, by personal opinion, is to use the
cocktails = ['Mojito', None, 'Pina Colada'] # Remove None values in list drinks = list(filter(None, cocktails)) print(drinks) # => ['Mojito', 'Pina Colada']
filter function takes a function and iterable as parameters, giving it the following signature:
filter(function, iterable). And the
filter function returns a filter object, so depending on your use-case you might want to cast it to a list again with
All elements that in the iterable are passed to the function. If the function returns
True for that specific element, that element is kept present. If it returns
False, it is filtered out.
If you pass
None as the function, the identity function is used instead. This causes all elements that are evaluated as
False to be filtered out, so besides
None empty strings, 0 and
False are too. Which can cause unwanted behavior.
true_and_false = [True, False, None, False, False, True] true_and_false = list(filter(None, true_and_false)) print(true_and_false) # => [True, True]
Thus, in the first example passing
None as a filter function does suffice. But in our cases you might need to be more explicit when you filter a list, to do you can use list comprehension or write your own callback function.
So the following example uses a lambda function to filter out
None values, but it keeps the
False's in there as well.
true_and_false = [True, False, None, False, False, True] # Filter out values with a lambda function true_and_false = list(filter(lambda x: x is not None, true_and_false)) print(true_and_false) # => [True, False, False, False, True]
And to include an example using list comprehension as well.
true_and_false = [True, False, None, False, False, True] # Filter out values with list comprehension true_and_false = [x for x in true_and_false if x is not None] print(true_and_false) # => [True, False, False, False, True]