Python list comprehension

jplindstrom on 2007-04-24T15:08:27

List comprehension in Python sounds cool and all, but it seems like it's "just" syntax for map and grep.

Or am I missing something?

(If nothing else, it's good to know what "list comprehension" is so you have at least an inkling of a clue when you encounter the phrase. The same goes for words like "tuple" (immutable list, right?).)

Actually even if it's just map and grep in sheep's clothing, syntax is rarely "just" anything.

A lot of times I've found that seemingly small things make a lot of difference usability-wise, and those small things make a huge actual difference in how you use or percieve something. There's a threshold value of resistance/friction to using anything, and when the friction is minute enough, that's when interesting things happen.

An example is how I use command completion.

Another is the way regular expressions are integrated into the Perl syntax. Looking at other languages where objects need to be created left and right to do the most simple things boggles the code reading mind.

Or the recent blog topic "we-can-fake-closures-with-objects-and-pretend-it's-the-same-thing".

So, is list comprehension different enough to make a difference?


map and filter (aka grep)

stvn_skuo on 2007-04-24T17:23:53

That's how I first viewed list comprehensions in Python (been studying it for a few months now). List comprehensions are idiomatic Python.

In certain cases, list comprehensions are faster than map and filter:

http://www.sacredchao.net/user/piman/writing/listcomp.shtml/

The Lisp-ish functions may be dropped in Python 3000 according to one well-known hacker:

http://www.artima.com/weblogs/viewpost.jsp?thread=98196