How to concatenate list members

Michael Chermside mcherm at destiny.com
Thu May 30 09:43:20 EDT 2002


Eric (at least half-jokingly):
 > If you like one-liners, you can also do this:
 >
 > b = (a and reduce(lambda x,y: x + "_" + y, a)) or ''

Rüdiger:
> Hello Eric,
> 
> Thanks for your solution (although I don't understand it).


Well, first of all, Eric was partly joking... this this is more 
difficult to read than his other solution, and therefore not 
particularly Pythonic. However, I'll attempt to interpret for you:

     b = (a and reduce(lambda x,y: x + "_" + y, a)) or ''
     b = <stuff>
We're simply setting b to some value.

    (a and reduce(lambda x,y: x + "_" + y, a)) or ''
    (a and <stuff_1>) or <stuff_2>
This pattern is a sort of if-else in one line. If bool(a) is True, it 
returns <stuff_1>, while if bool(a) is False, it returns <stuff_2>. So 
in this case, a is a list, and they're true if they have any elements.
So this returns <stuff_2> (ie '') if a is an empty list, and <stuff_1> 
(ie reduce(lambda x,y: x + "_" + y, a)) if a has elements.

     reduce(lambda x,y: x + "_" + y, a)
     reduce( <function(x,y)>, a )
The reduce() function takes a pair-wise function and keeps applying it 
to items in a sequence. So, for instance, if you used 
reduce(operator.add, range(10) it would calculate 0+1+2+3+4+5 = 10. The 
order of operations is like this: (((((0+1)+2)+3)+4)+5). So the function 
that we're applying is lambda x,y: x + "_" + y.


     lambda x,y: x + "_" + y
This is a lambda function which takes two things x and y and adds them 
together with "_". Since strings like "_" can only be added to other 
strings, x and y had better be strings. In which case, the function just 
glues them together with a "_" in between.

So... we we start upwrapping, we get this:
     Glue together with "_" ... all of the strings in a from left to
     right ... and return that if a has any items ... return '' instead
     if a is an empty list.


I realize that this was a HUGE amount of analysis on a simple looking 
line, but that's the way to approach these things if you don't 
understand them at first... take it in layers, from the outside in or 
the inside out. Hope this was informative at least!

-- Michael Chermside







More information about the Python-list mailing list