[Tutor] fancy list things
marilyn at deliberate.com
Thu Feb 5 19:48:57 EST 2004
On Fri, 6 Feb 2004, Karl Pflästerer wrote:
> 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()
> >>> reduce(lambda m, n: m+n, range(10), 0)
> So with some side effects you get something which looks a bit like
> reduce (but has nothing to do with it).
I'm sorry, I meant that you can't replace it with a list comprehension
of any sort? And zip() can't be replaced with any sort of list
> map() and filter() on the other hand can be replaced by list
> > 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 :-)
Is it only useful in map() and filter() and reduce()? And other
places where you want to hand a little function to a function? comp()
for example. Is there another class of examples?
I'm teaching python for the first time and want to be as solid as
possible on this stuff.
More information about the Tutor