Introduction
Calculating the sum of elements in a list is a common task in programming, particularly when working with numerical data. This tutorial will guide you through creating a Python program that calculates the sum of all elements in a given list.
Example:
-
Input:
[3, 5, 7, 2, 8] -
Output:
The sum of the elements is 25 -
Input:
[15, 22, 9, 3, 6, 27] -
Output:
The sum of the elements is 82
Problem Statement
Create a Python program that:
- Takes a list of numbers as input.
- Calculates the sum of all elements in the list.
- Displays the total sum.
Solution Steps
- Take Input from the User: Use the
input()function to get a list of numbers from the user. - Convert Input to a List of Integers: Convert the input string to a list of integers.
- Calculate the Sum of Elements: Use the
sum()function to calculate the sum of the elements in the list. - Display the Sum: Use the
print()function to display the sum.
Python Program
# Python Program to Find the Sum of Elements in a List
# Author: https://www.rameshfadatare.com/
# Step 1: Take input from the user
input_list = input("Enter a list of numbers separated by spaces: ")
# Step 2: Convert the input string to a list of integers
numbers = list(map(int, input_list.split()))
# Step 3: Calculate the sum of elements using the sum() function
total_sum = sum(numbers)
# Step 4: Display the sum
print(f"The sum of the elements is {total_sum}")
Explanation
Step 1: Take Input from the User
- The
input()function prompts the user to enter a list of numbers, separated by spaces. The input is stored as a string in the variableinput_list.
Step 2: Convert Input to a List of Integers
- The
split()method is used to split the input string into individual components, andmap(int, ...)is used to convert these components into integers. Thelist()function then creates a list of these integers.
Step 3: Calculate the Sum of Elements
- The
sum()function is used to calculate the sum of all elements in the list. The result is stored in the variabletotal_sum.
Step 4: Display the Sum
- The
print()function is used to display the total sum of the elements in the list.
Output Example
Example 1:
Enter a list of numbers separated by spaces: 3 5 7 2 8
The sum of the elements is 25
Example 2:
Enter a list of numbers separated by spaces: 15 22 9 3 6 27
The sum of the elements is 82
Example 3:
Enter a list of numbers separated by spaces: 10 20 30 40
The sum of the elements is 100
Conclusion
This Python program demonstrates how to calculate the sum of elements in a list using the sum() function. It’s a simple and efficient way to process numerical data in Python, making it an essential operation for data analysis and manipulation tasks.