Operators as functions

Peter Hansen peter at engcorp.com
Mon Dec 20 18:01:34 EST 2004


Anders Andersson wrote:
> I want to concatinate (I apologize for bad English, but it is not my 
> native language) a list of strings to a string. I could use (I think):
> 
> s = ""
> map(lambda x: s.append(x), theList)
> 
> But I want to do something like (I think that the code above is clumsy):
> 
> s = reduce("concatinating function", theList, "")
> 
> And here is the questions: What to replace "concatinating function" 
> with? Can I in some way give the +-operator as an argument to the reduce 
> function? I know operators can be sent as arguments in Haskell and since 
> Python has functions as map, filter and listcomprehension etc. I hope it 
> is possible in Python too. In Haskell I would write:

You are looking for "import operator", followed by a use of
operator.add in the reduce() call.  Note, however, that you
cannot add different types (generally) together, so you will
run into trouble if you take the "naive" approach and just
trying concatenating the strings and the list as you show
above.  Instead, you will need to pass the sequence of
things through a call to map(str, sequence) first, to call
the str() method on everything and make sure you are adding
strings together.  Thus:

import operator
s = reduce(operator.add, map(str, theList))

or something like that.

However, none of this is considered the best approach these days,
with the advent of list comprehensions and generator expressions.
Here's the old approach (shown above) and the shiny new modern
Pythonic approach (requires Python 2.4):

 >>> theList = range(10)
 >>> import operator
 >>> reduce(operator.add, map(str, theList))
'0123456789'
 >>> ''.join(str(x) for x in theList)
'0123456789'

-Peter



More information about the Python-list mailing list