0

I'm trying to iterate over a list of integers returned by a function.

Problem: i want to check if any element in the list is greater than a specific value (95), then perform a statement once, not for every iteration, i.e. go through the list, detect a number above 95 even if there are more, then perform the statement.

I've tried but the statement keep executing as many times the condition is met

here is a code i'm trying it on

for path in Path(spath).iterdir():
    for n in cosine_sim(file, path):
        x = all(n)
        if x > 95:
            print("suceess...")

the success... prints multiple times

wjandrea
  • 28,235
  • 9
  • 60
  • 81
X-Black...
  • 1,376
  • 2
  • 20
  • 28

3 Answers3

9

Python has built-in functions that do roughly what you want:

  • any(iterable) returns true if at least one element from iterable is truthy
  • all(iterable) returns true if every element from iterable is truthy

With that in mind, the general idiom for this is to check the condition on each element of your list, and then use all() or any() on it:

for n in cosine_sim(file, path):
    if all(x > 95 for x in n):
        print("success...")

This might be a bit slower than you want, because it actually has to calculate x > 95 for every x. If you're in a situation where you want to, say, make sure every number in your list nums is not equal to zero, or make sure that no string in strs is empty, you could just use all(nums) or all(strs) - since the number 0, and the empty string both evaluate as false, so you don't have to transform them into booleans first.

Green Cloak Guy
  • 23,793
  • 4
  • 33
  • 53
  • ...if all(x > 95 for x in n): TypeError: '>' not supported between instances of 'str' and 'int'... – X-Black... Jul 12 '19 at 13:19
  • Your data in `n` might be stored as strings instead of ints, in which case you'd need to do `int(x) > 95` instead. This type of solution can easily be tailored to any condition you need, depending on what type your data is and what the condition is that you need to check. – Green Cloak Guy Jul 12 '19 at 13:23
  • 1
    Note that `any` and `all` will short circuit as soon as a condition returns `True` or `False`, respectively. – wjandrea Jul 12 '19 at 13:54
1

Expanding Green Cloak Guy answer, with addition of break

for path in Path(spath).iterdir():
    for n in cosine_sim(file, path):
        if all(int(x) < 95 for x in n):
            print("suceess...")
            break
    break

two break because there are two loops...

X-Black...
  • 1,376
  • 2
  • 20
  • 28
0

You can also use this:

your_list=[123,232,121,100,98]

if any(i > 95 for i in your_list):
  print("success...")

t3m2
  • 366
  • 1
  • 15