sbb0
sbb0

Reputation: 55

Python 3 Testing a range of items within a list

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

Answers (4)

Arnab Ghosal
Arnab Ghosal

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

Ricardo Cárdenes
Ricardo Cárdenes

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

wim
wim

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

Andrew Clark
Andrew Clark

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

Related Questions