99

I'm trying to do a simple test that returns True if any of the results of a list are None. However, I want 0 and '' to not cause a return of True.

list_1 = [0, 1, None, 4] list_2 = [0, 1, 3, 4] any(list_1) is None >>>False any(list_2) is None >>>False 

As you can see, the any() function as it is isn't being helpful in this context.

1
  • 5
    Note that the current code means "if the result of my call to any happens to be None" (which, given that it will return True or False or raise an exception, will never happen). Commented Mar 3, 2015 at 16:09

2 Answers 2

190

For list objects can simply use a membership test:

None in list_1 

Like any(), the membership test on a list will scan all elements but short-circuit by returning as soon as a match is found.

any() returns True or False, never None, so your any(list_1) is None test is certainly not going anywhere. You'd have to pass in a generator expression for any() to iterate over, instead:

any(elem is None for elem in list_1) 
Sign up to request clarification or add additional context in comments.

9 Comments

And I'd quote that any Return True if any element of the iterable is true. If the iterable is empty, return False. So that was indeed not the right thing to use
@d6bels Not exactly. It's a perfectly natural use case of any(), you just need to combine it with a generator expression. in is fine in this case where list_1 is actually a List - in some cases it might be an arbitrary iterable without __contains__() implemented, and in such cases the any() solution would be the best option.
This will create troubles when the list contains Numpy arrays. Tom Cornebize has a better solution.
@frankliuao: but on numpy arrays you probably want to work with numpy.any() in any case, and not store None objects in a numeric array.
Note that this does not work if one of the list elements is a numpy array. In that case, first use list() on the array.
|
29
list_1 = [0, 1, None, 4] list_2 = [0, 1, 3, 4] any(x is None for x in list_1) >>>True any(x is None for x in list_2) >>>False 

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.