Reputation: 55
I have a list, or array, called inventory[] and it has a maximum of fifteen entries at any given time. I need to test if any of these entries is equal to zero, and if any one entry is equal to zero, do something. What is an efficient way to do this without doing
if inventory[0] == 0 or inventory[1] == 0 or inventory[2] == 0...
etc.?
Upvotes: 2
Views: 658
Reputation: 521
Try this out:
inventory=[1,2,3,4,0]
if 0 in inventory:
print "There is 0 in the list"
output: There is 0 in the list
Upvotes: 0
Reputation: 9172
Make use of the all
function, and the fact that 0
evaluates as False
:
if not all(inventory):
...
Edit: assuming that inventory
contains only numbers, of course
Upvotes: 0
Reputation: 362517
For your simple case, I think you could possibly just do this:
if 0 in inventory:
# do something
For a more general case for this type of thing, you can use the any
function (docs).
if any([item == 0 for item in inventory]):
# do something
Upvotes: 5
Reputation: 208415
Python's built-in any()
function is perfect for this. It takes an iterable as an argument and returns True
if any of the elements are true (non-falsy).
if any(item == 0 for item in inventory):
# do something
There is also a similar function called all()
that will return True
if all elements are True.
Upvotes: 2