Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Python equivalent of LINQ All function?

Tags:

python

linq

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?

like image 451
Cameron Avatar asked Dec 27 '11 04:12

Cameron


People also ask

Does Python have something like LINQ?

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.

Does Python has LINQ?

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#.

Does Java have something like LINQ?

There is nothing like LINQ for Java.

What is meant by LINQ in C#?

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.


1 Answers

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)
like image 191
DSM Avatar answered Sep 23 '22 07:09

DSM