Open In App

Find sum and average of List in Python

Last Updated : 27 Dec, 2024
Comments
Improve
Suggest changes
Like Article
Like
Report

In this article, we will explore various methods to find sum and average of List in Python. The simplest way to do is by using a built-in method sum() and len().

Using sum() and len()

Python provides convenient built-in functions like sum() and len() to quickly calculate the sum and length of list respectively.

Python
a = [10, 20, 30, 40, 50]

# Finding sum using built-in sum() function
totalSum = sum(a)

# Finding average using built-in sum() and len() functions
average = totalSum / len(a) if a else 0  # Avoid division by zero

print("Sum of the list:", totalSum)
print("Average of the list:", average)

Output
Sum of the list: 150
Average of the list: 30.0

Explanation:

  • sum(a): Calculates sum of numbers in the list ‘a‘.
  • len(a): Returns number of elements in the list ‘a‘.
  • average = totalSum / len(a): This compute the average. We also check if the list is not empty to avoid division by zero.

Using Loop

If we’d like to manually calculate the sum and average without using built-in functions then we can find this by looping through the list.

Python
a = [10, 20, 30, 40, 50]

# To store the total sum
totalSum = 0

# To store length of list 'a'
length = 0

# Finding sum using a loop
for val in a:
    totalSum += val
    length += 1

# Finding average manually
average = totalSum / length if a else 0  # Avoid division by zero

print("Sum of the list:", totalSum)
print("Average of the list:", average)

Output
Sum of the list: 150
Average of the list: 30.0

Explanation: We iterate over the list ‘a’ and calculate their sum and length. And to find the average divide total calculated sum by length of list.




Next Article

Similar Reads