To find the sum of the squares of a list of numbers in Python, the easiest way is with a for loop.
def sum_of_squares(lst):
sum = 0
for x in lst:
sum = sum + x ** 2
return sum
print(sum_of_squares(range(10))) # range(0,1,2,3,4,5,6,7,8,9)
print(sum_of_squares([4,6,2,9,10]))
#Output:
285
237
You can also use sum() and list comprehension to find the sum of squares of a list of numbers in Python.
def sum_of_squares(lst):
return sum([x ** 2 for x in lst])
print(sum_of_squares(range(10))) # range(0,1,2,3,4,5,6,7,8,9)
print(sum_of_squares([4,6,2,9,10]))
#Output:
285
237
If you want to calculate the sum of squares for the first N numbers, you can use the following formula.
def sum_of_squares_first_n(n):
return (n * (n + 1) * (2 * n + 1)) // 6
print(sum_of_squares_first_n(5))
#Output:
55
When working with collections of numbers, the ability to easily summarize these collections can be useful.
One such calculation which is necessary sometimes is the sum of squares of a list of numbers.
The easiest way to get the sum of squares of a list of numbers in Python is with a for loop.
You can get the sum of squares of a list of numbers with a for loop by simply adding up the square of each number in a given list or range.
Below is an example which shows you how to use a for loop to get the sum of squares of a list in Python.
def sum_of_squares(lst):
sum = 0
for x in lst:
sum = sum + x ** 2
return sum
print(sum_of_squares(range(10))) # range(0,1,2,3,4,5,6,7,8,9)
print(sum_of_squares([4,6,2,9,10]))
#Output:
285
237
Using List Comprehension to Find Sum of Squares in Python
You can also use the sum() function and list comprehension to find the sum of squares of a list of numbers using Python.
For basic operations, wherever you use a for loop, it’s probable you can use list comprehension.
Below shows you how you can use list comprehension to get the sum of squares of a list in Python.
def sum_of_squares(lst):
return sum([x ** 2 for x in lst])
print(sum_of_squares(range(10))) # range(0,1,2,3,4,5,6,7,8,9)
print(sum_of_squares([4,6,2,9,10]))
#Output:
285
237
Find Sum of Squares of First N Numbers with Formula in Python
For the first n numbers, there exists a formula which you can use which will give you the sum of the squares.
The sum of squares for the first n numbers is:
(n * (n + 1) * (2 * n + 1)) / 6
Below is a simple function which will get the sum of the squares of the first n numbers using Python. Note the use of integer division to return an integer value.
def sum_of_squares_first_n(n):
return (n * (n + 1) * (2 * n + 1)) // 6
print(sum_of_squares_first_n(5))
#Output:
55
Hopefully this article has been useful for you to learn how to find the sum of squares in a list of numbers using Python.