Python List Comprehension…and C#

In Python List comprehensions provide a concise way to create lists.
To build them, you use brackets which contain an express that is followed by a for clause. You can add zero or more for or if clauses. Since you can put all kinds of objects inside a list, the expression can be anything.

What do we get when we do that? A new list which is the result of evaluating the expression in the context of the clauses that have been passed.

Using this concept of “list comprehension”, we can act like mathematicians and construct list in a very natural way.

The following are common ways to describe lists (or sets, or tuples, or vectors) in mathematics.

S = {x² : x in {0 … 5}}
V = (1, 2, 4, 8, …, 2¹²)
M = {x | x in S and x odd}
N = {x | x in S and x even}

You probably know things like the above from mathematics lessons at school. In Python, you can write these expression almost exactly like a mathematician would do, without having to remember any special cryptic syntax.

This is how you do the above in Python:

>>> S = [x**2 for x in range(6)]
>>> V = [2**i for i in range(13)]
>>> M = [x for x in S if x % 2 != 0]
>>> N = [x for x in S if x % 2 == 0]

>>> print S; print V; print M
[0, 1, 4, 9, 16, 25]
[1, 2, 4, 8, 16, 32, 64, 128, 256, 512, 1024, 2048, 4096]
[1, 9, 25]
[0, 4, 16]

Some more complex examples are available online.
This is a very interesting concept which is worth understanding.

The same thing in C#

Python has a pretty succinct syntax for building list comprehension. C# provides us with a similar functionality by the use of LINQ. Here are examples:

List<Foo> fooList = new List<Foo>();
IEnumerable<string> extract = fooList.Where(foo => foo.Bar > 10).Select(foo => foo.Name.ToUpper());

Also List<T>.ConvertAll behaves just like list comprehensions by performing the same operation on every item on an existing list and then returning a new collection. This is an alternative to using Linq especially if you are still using .NET 2.0. It converts the elements in the current List<T> to another type, and returns a list containing the converted elements.
The following is a Python example followed by the equivalent C# example.

>>> foo = [1, 2, 3]
>>> bar = [x * 2 for x in foo]
>>> bar
[2, 4, 6]

C# (3.0 and higher) example follows:

public static void Main()
var foo = new List<int>{ 1, 2, 3};
var bar = foo.ConvertAll(x => x * 2); // list comprehension

foreach (var x in bar)
Console.WriteLine(x); // should print 2 4 6

Have fun 🙂


Leave a Reply

Fill in your details below or click an icon to log in: Logo

You are commenting using your account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s

%d bloggers like this: