[Tutor] Adding Lists?

bob gailer bgailer at gmail.com
Sun Aug 24 03:03:37 CEST 2008


Alan Gauld wrote:
>
> "Emile van Sebille" <emile at fenx.com> wrote
>
>>> yet if i wrote range (1, 500, 2) [1, 3, 5, 7....... ..499] is there 
>>> a command where i could total that list quickly?
>>>
>>
>> You're looking for sum --
>>  sum(range (1, 500, 2) )
>
> Or on older Python versions reduce:
>
> import operator
> s = reduce(operator.add, range(1,500,2))

This is good to know about, as:

(1) the operator module has methods for all native operators
     e.g., s = reduce(operator.mul, range(1,500,2)) to get the product.

(2) one may use any function as the first argument to reduce
    e.g., reduce(lambda x, y: x+y, [1, 2, 3, 4, 5])
    calculates ((((1+2)+3)+4)+5) (the sum)


-- 
Bob Gailer
Chapel Hill NC 
919-636-4239

When we take the time to be aware of our feelings and 
needs we have more satisfying interatctions with others.

Nonviolent Communication provides tools for this awareness.

As a coach and trainer I can assist you in learning this process.

What is YOUR biggest relationship challenge?



More information about the Tutor mailing list