[Tutor] fancy list things

Karl Pflästerer sigurd at 12move.de
Thu Feb 5 19:17:01 EST 2004


On  6 Feb 2004, Marilyn Davis <- marilyn at deliberate.com wrote:

> Is it true that you can *always* replace map() and filter() with a
> list comprehension?  But you can never replace reduce()?

Yes. No (well it is possible but extremly ugly):

>>> class Foo:
...     def __init__(self, x):
...             self.x = x
...     def set (self, v):
...             self.x += v
...             return self.x
... 
>>> [f.set(e) for e in range(10)].pop()
45
>>> reduce(lambda m, n: m+n, range(10), 0)
45

So with some side effects you get something which looks a bit like
reduce (but has nothing to do with it).

map() and filter() on the other hand can be replaced by list
comprehensions.


> Can anyone give me a reasonable example of lambda?

What do you mean exactly?  Lambda calculus? Lambda in Python?

In Python lambda can be used to build simple (very simple sadly)
anonymous expressions (no statements) which can get used at places where
you think it's not worth writing a function with a name.  But their
usage is very weakly in Python, you can't compare it with languages like
Lisp (CL, Scheme) or Haskell.  But that's no bug it's a feature :-)



   Karl
-- 
Please do *not* send copies of replies to me.
I read the list




More information about the Tutor mailing list