using lambda to print everything in a list

Christian Tanzer tanzer at swing.co.at
Mon Apr 30 04:10:36 EDT 2001


"Alex Martelli" <aleaxit at yahoo.com> wrote:

> "Christian Tanzer" <tanzer at swing.co.at> wrote in message
> news:mailman.988463382.11255.python-list at python.org...
> 
> """
> "Alex Martelli" <aleaxit at yahoo.com> wrote:
> > My personal impression is that lambda is a (minor)
> > nuisance.  Naming the code fragment that you want
> > to pass to some other function, by making it a
> > nested function, seems clearer & handier to me.
> 
> What about using `map' to apply a method to each element in a list?
> Like in:
>     map (lambda s : s.capitalize (), l)
> I wouldn't call a loop clearer in this case, despite the lambda.
> """
> 
> Some of the equivalent alternatives are:
> 
> # 1. your lambda
> L = map(lambda s: s.capitalize(), l)
> 
> # 2. list comprehension
> L = [s.capitalize() for s in l]
> 
> # 3. plain append-loop
> L = []
> for s in l: L.append(s.capitalize())
> 
> # 4. special case, as you note, for string. stuff
> L = map(string.capitalize, l)
> 
> # 5. a named local function
> def toUpper(s): return s.capitalize()
> L = map(toUpper, l)
> 
> There doesn't seem to be a huge clarity difference among
> this set of possibilities, but my personal vote for clarity
> order would be, roughly, 2-4-5-3-1.  Others' tastes will no
> doubt differ.  

Please note, that things like `string.capitalize' are restricted to
homogeneous collections of strings. For polymorphic collections it
will break. 

For me, that puts the clarity of `#4' at the bottom of the list
(though I didn't think about it when posting about this topic first
:( ).

IMHO, `#3' has the big disadvantage of failing to convey the intention
of the code. All solutions using map or list comprehensions are
concise expressions that can be used directly in every context
(both in statements and expressions). A loop based solution adds
unnecessary statements to the context and distract from the context's
intention.

`#5' either means that you break the flow of code with an unnecessary
(to the context) def statement or the reader of the code must look
around to find the definition of the ad-hoc function `toUpper'. 

> But it seems to me that, even in a case as simple as this one, lambda
> isn't really "pulling its weight" as a language feature. It gets worse
> as soon as you need to do anything substantial, IMHO...

Which is why list comprehensions are a welcome addition to Python even
though they are just syntactic sugar. Unfortunately, I'm still stuck
with supporting 1.5.2 and will be so for some months. 

-- 
Christian Tanzer                                         tanzer at swing.co.at
Glasauergasse 32                                       Tel: +43 1 876 62 36
A-1130 Vienna, Austria                                 Fax: +43 1 877 66 92





More information about the Python-list mailing list