18

What is the idiomatic Python way to test if all elements in a collection satisfy a condition? (The .NET All() method fills this niche nicely in C#.)

There's the obvious loop method:

all_match = True
for x in stuff:
    if not test(x):
        all_match = False
        break

And a list comprehension could do the trick, but seems wasteful:

all_match = len([ False for x in stuff if not test(x) ]) > 0

There's got to be something more elegant... What am I missing?

Cameron
  • 96,106
  • 25
  • 196
  • 225

1 Answers1

28
all_match = all(test(x) for x in stuff)

This short-circuits and doesn't require stuff to be a list -- anything iterable will work -- so has several nice features.

There's also the analogous

any_match = any(test(x) for x in stuff)
DSM
  • 342,061
  • 65
  • 592
  • 494
  • 1
    Definitely the way I'd go. However, `all` in Python differs from `Enumerable.All` in that it does not directly take a predicate. (So it's more akin to `Enumerable.Where(predicate).All()`.) –  Dec 27 '11 at 04:45