Python equivalents to LINQ

Viewed 29921

In C#, with LINQ, if I have en enumeration enumerable, I can do:

// a: Does the enumerable contain an item that satisfies the lambda?
bool contains = enumerable.Any(lambda);

// b: How many items satisfy the lambda?
int count = enumerable.Count(lambda);

// c: Return an enumerable that contains only distinct elements according to my custom comparer
var distinct = enumerable.Distinct(comparer);

// d: Return the first element that satisfies the lambda, or throws an exception if none
var element = enumerable.First(lambda);

// e: Returns an enumerable containing all the elements except those
// that are also in 'other', equality being defined by my comparer
var except = enumerable.Except(other, comparer);

I hear that Python has a more concise syntax than C# (and is therefore more productive), so how do I achieve the same with an iterable in Python, with the same amount of code, or less?

Note: I don't want to materialize the iterable into a list if I don't have to (Any, Count, First).

3 Answers

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:

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.

Related