19

To demonstrate I have done sth. This is my code do sum in three lines.

l=[1,2,3,4,5];
sumOfList=0

for i in l:
    sumOfList+=i*i;
print sumOfList

I am curious can I do it in just one line?

1
  • 7
    You shouldn't use sum as a name for your variable for it shadows the builtin sum.
    – Matthias
    Nov 12, 2014 at 18:50

5 Answers 5

30

Yes, you can. Here it is using the sum function:

l = [1,2,3,4,5]
print(sum(i*i for i in l))
0
22

What about :

sum(map(lambda x:x*x,l))

we also use reduce:

print reduce(lambda x,y: x+y*y,l) # as pointed by @espang reduce(lambda x,y: x+y*y,l) is only ok, when the first value is 1 (because 1*1 == 1). The first value is not squared

We can take the first element, get its square, then add it to the head of the list so we can make sure that it's squared. Then we continue using reduce. It isn't worth all that work, as we have better alternatives.

reduce(lambda x,y: x+y*y,[l[:1][0]**2]+l[1:])

Just out of curiosity, I tried to compare the three solutions to sum the squares of 10000 numbers generated by range, and compute the execution time of every operation.

l=range(10000) 
from datetime import datetime
start_time = datetime.now()
print reduce(lambda x,y: x+y*y,l)
print('using Reduce numbers: {}'.format(datetime.now() - start_time))

from datetime import datetime
start_time = datetime.now()
print sum(map(lambda x:x*x,l))
print('Sum after map square operation: {}'.format(datetime.now() - start_time))

from datetime import datetime
start_time = datetime.now()
print sum( i*i for i in l)
print('using list comprehension to sum: {}'.format(datetime.now() - start_time))

Output:

Using list comprehension is faster

333283335000
using Reduce numbers: 0:00:00.003371
333283335000
Sum after map square operation: 0:00:00.002044
333283335000
using list comprehension to sum: 0:00:00.000916
6
  • docs.python.org/2/tutorial/… This is also equivalent to squares = map(lambda x: x**2, range(10)), but it’s more concise and readable.
    – AlexWei
    Nov 12, 2014 at 19:00
  • 2
    reduce(lambda x,y: x+y*y,l) is only ok, when the first value is 1 (because 1*1 == 1). The first value is not squared
    – espang
    Nov 12, 2014 at 19:02
  • same result. List comprehension is fastest
    – AlexWei
    Nov 12, 2014 at 19:04
  • @espang may be we can trick it by extracting the first element, get the square number and then add it to the rest of the list reduce(lambda x,y: x+y*y,[l[:1][0]**2]+l[1:]) But it doesn't worth all that work as we have better alternatives
    – user4179775
    Nov 12, 2014 at 19:09
  • 1
    why this overly complex idea for such a simple thing. it's not a list comprehension by the way it's a generator expression.
    – wim
    Nov 12, 2014 at 19:13
15

For bigger list and when performance matters you should use numpy:

import numpy as np
l = [1,2,3,4,5]
arr = np.array(l)

np.sum(arr**2)
# or better:
np.dot(arr, arr)
2
  • at what size list should one consider using numpy over base python?
    – baxx
    Jul 3, 2019 at 22:11
  • 2
    @baxx I compared sum(i*i for i in range(15)), with a=np.arange(15), np.dot(a,a). It was a tie (even after adding the time to include numpy as np! Any number larger than 15, and numpy is much faster. Sep 3, 2019 at 10:54
0

You could define a function and use list comprehension

l = [2, 6, 10, 12, 16, 20]

def sumOfSquares(alist):
return ((sum([i**2 for i in alist]))-(sum(alist)**2)/len(alist))

print(sumOfSquares(l))
0
l = [1, 2, 3, 4, 5, 6]

sum(np.multiply(l,l))

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

Not the answer you're looking for? Browse other questions tagged or ask your own question.