Progress

Python Program to sum all elements in List or Tuple

Python Program to sum all elements in List or Tuple

List and tuples are one of the most important data structures of Python programming languages. It is a general problem to sum all the elements in any list or tuple while writing any Python code.

There are multiple ways to solve a problem in Python which depends upon the problem type.

Python Program: Sum all elements in list or tuple using for loop

This is general approach to solve this problem. It is popular way to sum all the elements of array and other data structures which support indexing.

Copy
numList = [1,2,3,4,5]

#Uncomment below line to take user input
#numList = list(map(int,input("Enter numbers separated by space\n").split(" ")))

added = 0
for i in range(len(numList)):
    added+=numList[i]
print(added)

The logic of this Python code is very simple.

We initialize a list at the very first line. Then we looped through the list and add each element to the variable added.

Finally, we print the total result store in variable added.

Alternative: Use of in operator

Insted of looping through the iterable we can also use a simple approach.

The in operator in Python is a way to iterate through any iterable (list, tuple etc.) and perform any operation.

Copy
numList = [1,2,3,4,5]
added = 0
for item in numList:
    added+=item
print(added)

In this Python code we iterated through the list and add each element to get the sum of all elements in the list.

Python Program: Sum all elements in any List, tuple or iterable using the sum function

The easiest way to find sum of all elements in any list, tuple or iterable is to use inbuilt sum() function.

The sum() function in Python takes an argument of an iterable (list, tuple, set etc.), calculates the sum of all its elements and return sum value of type integer.

Copy
numList = [1,2,3,4,5]
total = sum(numList)
print(total)
Output
15

As simple as it seems. The sum() function takes the list numList and returns the total sum of all elements in that list.

The sum function also works in the same way for tuple and set.

Copy
sum((1,2,3,4,5)) # Sum of all elements of tuple
sum({1,2,3,4,5}) # Sum of all elements of a set

One line Solution in Python (Advanced)

Copy
print(sum(list(map(int,input("Enter numbers separated by space: ").split(" ")))))
Output
Enter numbers separated by space: 1 2 3 4 5
15

We try to add one line of solution to every Python example wherever possible. This represents the beauty of Python can be unmatched and creativity is the limit.

At the very first step, the code takes input from the user and split it on the basis of space.

Then map function maps each item of the list returned from split() to int() function to convert it to the integer type.

The third step is to convert the map object to list.

The sum() function calculates the sum of all elements in the list and at last, we print the result.

Some more python Example:

Share the Post ;)

Related Posts