[Tutor] List comprehension

Charlie Clark charlie@begeistert.org
Fri Apr 11 04:51:02 2003


On 2003-04-11 at 06:36:02 [+0200], tutor-request@python.org wrote:
> Subject: [Tutor] List comprehension
> 
> Dear List-ers,
> 
> How can I simplify this lines:
>     > sum = 0
>     > myList = [1,2,3,4,5,6]
>     > for each in myList:
>     >    sum += each
> 
> Into shorter, more elegant line(s)?

Although Albert has shown you how to do this with reduce() I don't actually 
think there is any need to shorten or make this more elegant.

compare
sum = reduce(operator.add, myList)
with
for x in myList: sum += x

which is shorter? which is more elegant?
reduce() is shorter and returns the desired value directly but I personally 
have to look reduce() up in a book every time I see it. But I think you 
wanted to know if you could do this with list (in)comprehensions. I don't 
think so as they always return lists, ie. you might expect
[sum + x for x in myList]
but this just adds "sum" to each value in the list and returns a new list 
with these calculated values.

Charlie