[Tutor] The Zen of List Comprehension

Alan Gauld alan.gauld at blueyonder.co.uk
Mon Aug 18 10:07:39 EDT 2003


> of elements, as a basic tool, then having special functions for
these
> operations makes no more sense than having a function like
> assignVariable(x=1). Since assignment is an essential operation,

And here you raise another thorny issue since one of the features
of pure FP is that assignment is NOT an essential operation but
in fact is something to avoid. Indeed the grandaddy of FP languages
Lisp has no assignment operation as we know it but uses a function
to do assignment:

(set x 7)

:-)

> likewise needless verbiage. Instead of saying filter(), just filter

OK, But the name 'filter' is there as a reminder of the purpose of
the function. Its a readability issue as much as anything. If I'm
scanning the code I don;t need to know whatexactly is being
filtered I just know that something has been filtered out of
the list into a new list. Whereas with a LC I have to read the
internal detail even to know that a filter has happened!

> Add the limitation of operations on single anonymous variables,
> and the resultant profusion of lambdas

Yes but the intent is not that you put lambdas in map and filter
but that you put real named functions:

def square(x): return x*x
map(square,aList)

As I've said many times lambdas are just a coincidental feature
of how many folks use map/filter etc, they are not a necessary
element. Now of course for simple one-liner funtions like above
it is more work to create the function than to use a lambda,
and much more so than to use an inline expression, the improvement
in readability is significant.

> The one thing I still don't understand is whether list comps are
valid
> functional programming constructs. Does

Yes they are. Any book on discrete math will include how to describe
list comprehensions. Its a fundamental part of the subject the ability
to describe a list and its contents.

The FP approach however is to use LC as the list initialiser then
apply list operations(like filter, map etc) to modify the list.
In FP LCs are kind of like constructors for lists.

Alan G.




More information about the Tutor mailing list