Introducing Python to others

andrew cooke andrew at acooke.org
Tue Mar 31 18:06:07 CEST 2009


David C. Ullrich wrote:
> In article <TM6dnZxRVIQ0QFbUnZ2dnUVZ_rmdnZ2d at pdx.net>,
>  Scott David Daniels <Scott.Daniels at Acm.Org> wrote:
>
>> Mensanator wrote:
>> > On Mar 26, 11:42 am, "andrew cooke" <and... at acooke.org> wrote:
>> >> ...
>> >> that's cute, but if you show them 2.6 or 3 it's even cuter:
>> >>
>> >>>>> from operator import add
>> >>>>> class Vector(list):
>> >> ...   def __add__(self, other):
>> >> ...     return map(add, self, other)
>> >> ...>>> x = Vector([1,2])
>> >>>>> x+x
>> >> [2, 4]
>> >
>> > What would you have to do to make this work?
>> >
>> >>>> x+x+x      # expecting [3,6]
>> > [2, 4, 1, 2]
>> >
>>
>>      class Vector(list):
>>          def __add__(self, other):
>>              return type(self)(x + y for x, y in zip(self, other))
>
> Question: I would have thought it would be
>
>       return type(self)([x + y for x, y in zip(self, other)])
>
> What's this thing that looks like a list comprehension but isn't?

it's a generator expression. 
http://docs.python.org/3.0/reference/expressions.html#index-3735

andrew




More information about the Python-list mailing list