Monday, February 23, 2009

List Comprehensions

I love them. They're just so Pythonic.

What they do is provide you a succinct way to describe a list. You know, our favourite little squiggly snakes with [] at the ends. If you haven't the foggiest what a list comprehension is (and you'd be missing out on a lot of fun), here's a little example to get your juices flowing. Let's say, just for argument's sake, you want to represent the following mathematical expression in your program:

M = {x| x in S and x odd}

How would you do that in Java? You would likely go:

ArrayList M = new ArrayList();

for (int x: S) {
  if (x % 2 == 1)
    M.add(x);
}

How utterly clumsy and unPythonic. In Python you'd just do this:

M = [x for x in S if x % 2 == 1]

So easily comprehensible that anyone not well-versed in Python's syntax could probably guess what it is doing, and very, very snug, spanning only one line! (Then again, snakes do have a reputation of having flexible bodies. ;) ) Doesn't it make you say, “If only [insert here your favourite language before you fell in love with the beauty that is Python] had such awesome syntax?”

So next time you have the urge to create a list in your super-duper Python program (and the urge should be often), do it the Python way. Now, please excuse me while I go off to drool at all the posters of Pythonidae in my bedroom ;).

No comments:

Post a Comment