Operators as functions

Steven Bethard steven.bethard at gmail.com
Mon Dec 20 18:19:24 EST 2004


Peter Hansen wrote:
> 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'

Also worth noting is that the shiny new modern version is also the 
faster version:

$ python -m timeit -s "import operator; L = range(10000)" 
"reduce(operator.add, map(str, L))"
10 loops, best of 3: 89.9 msec per loop

$ python -m timeit -s "L = range(10000)" "''.join(str(x) for x in L)"
100 loops, best of 3: 15.3 msec per loop

[run with Python 2.4 on a 2.26GHz Pentium 4]

Steve



More information about the Python-list mailing list