-1

My question is quite similar to How to check if all elements of a list matches a condition. But I couldn't find a right way to do the same thing in a for loop. For example, using all in python is like:

>>> items = [[1, 2, 0], [1, 0, 1], [1, 2, 0]]
>>> all(item[2] == 0 for item in items)
False

But when I want to use the similar method to check all elements in a for loop like this

>>> for item in items:
>>>    if item[2] == 0:
>>>        do sth
>>>    elif all(item[1] != 0)
>>>        do sth

The "all" expression cannot be used in here. Is there any possible way like "elif all(item[2] == 0)" to be used here. And how to check if all elements in list match a condition in a for loop?

Community
  • 1
  • 1
American curl
  • 1,259
  • 2
  • 18
  • 21
  • Why would you want to use a loop, if Python has built-in uses like `all` and `any`? – Nander Speerstra Aug 03 '16 at 08:12
  • Because I have one For loop, and a if condition. I just want to add an else condition to check if all elements match one condition. And I just want to know is there a simple way for using 'all' and 'any' in this scenario? – American curl Aug 03 '16 at 08:19

6 Answers6

2

If you want to have an if and an else, you can still use the any method:

if any(item[2] == 0 for item in items):
    print('There is an item with item[2] == 0')
else:
    print('There is no item with item[2] == 0')

The any comes from this answer.

Community
  • 1
  • 1
Nander Speerstra
  • 1,496
  • 6
  • 24
  • 29
1

Here:

items = [[1, 2, 0], [1, 0, 1], [1, 2, 0]]

def check_list(items): 
    for item in items:
        if item[2] != 0:
            return False
    return True

print(check_list(items))

If you want to make it a bit more generic:

def my_all(enumerable, condition):
    for item in enumerable:
        if not condition(item):
            return False
    return True

print(my_all(items, lambda x: x[2]==0)
adessy
  • 87
  • 5
dheiberg
  • 1,914
  • 14
  • 18
0

Try This:-

prinBool = True
for item in items:
    if item[2] != 0:
     prinBool = False
     break
print prinBool
Rakesh Kumar
  • 4,319
  • 2
  • 17
  • 30
0

You could use a for loop with the else clause:

for item in items:
    if item[2] != 0:
       print False
       break
else:
    print True

The statements after else are executed when the items of a sequence are exhausted, i.e. when the loop wasn't terminated by a break.

Eugene Yarmash
  • 142,882
  • 41
  • 325
  • 378
0

With functools, it will be easier :

from functools import reduce

items = [[1, 2, 0], [1, 0, 1], [1, 2, 0]]
f = lambda y,x : y and x[2] == 0  
reduce(f,items)
Nander Speerstra
  • 1,496
  • 6
  • 24
  • 29
mandrewcito
  • 170
  • 8
-1

Do you mean something like this?

for item in items:
    for x in range (0,3):
        if item[x] == 0:
            print "True"
63.AMG
  • 1