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?
With LINQ, we can write functions in an intuitive, fluent and readable way. Python doesn't have an exact analog of LINQ. However, we can get something similar using some of Python's built-in functions.
LINQ (Language Integrated Query) is a query language to deal with the query operators to perform the operations with the collections. In Python, we are able to achieve LINQ methods like C#.
There is nothing like LINQ for Java.
Language-Integrated Query (LINQ) is the name for a set of technologies based on the integration of query capabilities directly into the C# language. Traditionally, queries against data are expressed as simple strings without type checking at compile time or IntelliSense support.
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)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With