Python equivalents to LINQ

We have generator expressions and various functions for expressing arbitrary conditions over iterables.

any(some_function(e) for e in iterable)
sum(1 for e in iterable if some_function(e))
set(iterable)
next(iterable)
(e for e in iterable if not comparer(e) in other)

would roughly correspond to how you write your examples in idiomatic Python.


The original question was how to achieve the same functionality with iterables in Python. As much as I enjoy list comprehensions, I still find LINQ more readable, intuitive and concise in many situations. The following libraries wrap Python iterables to achieve the same functionality in Python with the same LINQ semantics:

  • py_linq
  • Linq

If you want to stick with built in Python functionality, this blog post provides a fairly thorough mapping of C# LINQ functionality to built-in Python commands.


The following Python lines should be equivalent to what you have (assuming func, or lambda in your code, returns a Boolean):

# Any
contains = any(func(x) for x in enumerable)

# Count
count = sum(func(x) for x in enumerable)

# Distinct: since we are using a custom comparer here, we need a loop to keep 
# track of what has been seen already
distinct = []
seen = set()
for x in enumerable:
    comp = comparer(x)
    if not comp in seen:
        seen.add(comp)
        distinct.append(x)

# First
element = next(iter(enumerable))

# Except
except_ = [x for x in enumerable if not comparer(x) in other]

References:

  • List comprehensions
  • Generator expressions
  • any() built-in function
  • sum() built-in function
  • set type

Note that I renamed lambda to func since lambda is a keyword in Python, and I renamed except to except_ for the same reason.

Note that you could also use map() instead of the comprehensions/generators, but it is generally considered less readable.