Python equivalents to LINQ

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.

Leave a Comment