3. Problem to print the sum of all elements in a list.

In this program, we will take a user input as a list & iterate all the values one by one with the python loop to find the sum of all elements in a list.

Table of Contents

Method 1: Using for loop

Steps to solve the program
  1. Take a list as input.
  2. Use for loop to iterate over every element of the list.
  3. Find and print the sum of all elements of the list using the appropriate condition.
				
					#Input list
list1 = [2,5,8,0,1]

#Creating a variable
var = 0

for value in list1:
    var += value

print(var)
				
			

Output :

				
					
16
				
			

Method 2 : Using while loop

Steps to solve the program
  1. Take a list as input.
  2. Using while loop and necessary condition find and print the sum of all elements of the list.
				
					#Input list
list1 = [2,5,8,0,1]

#Creating variable
count = 0
total = 0

while count < len(list1):
    total += list1[count]
    count += 1

#Printing output
print(total)
				
			

Output :

				
					16
				
			

Method 3 : Using sum() function

Steps to solve the program
  1. Take a list as input.
  2. Use sum() function to find the sum of all the elements of the list.
				
					#Input list
list1 = [2,5,8,0,1]

#Printing output
print(sum(list1))
				
			

Output :

				
					16
				
			

Related Articles

 Combine two lists

Product of all elements

1 thought on “3. Problem to print the sum of all elements in a list.”

Leave a Comment