Home > Programming & scripting, Python > Why I think map and filter is more “pythonic” than list comprehension

Why I think map and filter is more “pythonic” than list comprehension

April 19th, 2007

I don’t really like the word pythonic, but I do kind of understand what the basic concept is.

That being said, I can’t see why people prefer list comprehension before map and filter, and there are even rumors about removing them from the language.

Let’s just take a common example: converting a string into it’s integer ordinal values.

First there is the “classical” approach, defining a new list, iterating through the string and appending each ordinal into the new list… something like this

text = "some words"
ordinals = []
for c in text:
  ordinals.append(ord(c))

This is obviously unpythonic.
Let’s have a look at the list comprehension method

ordinals = [ord(c) for c in text]

MUCH BETTER! But here is the catch… we still need the temporary variable c (which will even be declared in the global scope afterwards in python 2.4, haven’t checked in 2.5 yet). This is good, but map makes it even better.

ordinals = map(ord, text)

This is so straight forward that it can’t be misunderstood. While list comprehension translated to regular text would be something like:
“For each character in text, assign it to the variable c and then append ord(c) to the list to return”.
Map would simply translate into:
“For each character in text, apply ord to it and append the result to the list to return”.
There is no side effects and it is even easier to read.

Let’s have at one of the explanation of the word pythonic that I usually see gets passed around.

The text in there is pretty obvious, but let’s just have a look at one of the examples.

Unpythonic:

for (i=0; i < mylist_length; i++) {
   do_something(mylist[i]);
}

Pythonic:

for element in mylist:
   do_something(element)

The pythonic version clearly abstracts the underlying implementation, and is much easier to read, without needing any extra variables for iterating through the iterator… kind of like map and filter compared to list comprehension?

There is however one thing that list comprehension does better than map and filter, and that is applying multiple mapped functions or filters at only one passing. However using simply this as a reason for removing map and filter from the language feels somewhat silly.

buffi Programming & scripting, Python

  1. No comments yet.
  1. No trackbacks yet.