convert loop to list comprehension

Felipe Almeida Lessa felipe.lessa at gmail.com
Fri Sep 8 20:56:40 EDT 2006


08 Sep 2006 17:33:20 -0700, Paul Rubin <"http://phr.cx"@nospam.invalid>:
> bearophileHUGS at lycos.com writes:
> > print sum( ([i]*n for i,n in enumerate(seq)), [])
>
> Wow, I had no idea you could do that.  After all the discussion about
> summing strings, I'm astonished.

Why? You already had the answer: summing *strings*. Everything but
strings can be summed by sum(). E.g.:

Python 2.4.3 (#2, Apr 27 2006, 14:43:58)
[GCC 4.0.3 (Ubuntu 4.0.3-1ubuntu5)] on linux2
Type "help", "copyright", "credits" or "license" for more information.
>>> class x(object):
...     def __add__(self, other):
...             return x(self.a + other.a)
...     def __init__(self, a):
...             self.a = a
...
>>> t = x(10)
>>> t.a
10
>>> sum([t, t])
Traceback (most recent call last):
  File "<stdin>", line 1, in ?
TypeError: unsupported operand type(s) for +: 'int' and 'x'
>>> sum([t, t], t)
<__main__.x object at 0xb7d6752c>
>>> _.a
30
>>> sum([t, t], x(0)).a
20
>>> sum([t, t]*1000, t).a
20010


-- 
Felipe.



More information about the Python-list mailing list