Write a python program to sum all the numbers in a list
In this exercise, you will learn different ways to get the sum of list using the Python programming language. Such a type of question is generally asked in an interview or competitive examination.
Method 1: Using For loop
Here is the Python program to sum all the numbers in a list using the for loop. First, we receive elements of the list from user input using a predefined function input() and use the for loop to iterate each element in this list. In each iteration, we are adding those elements to the total variable and getting the sum at last.
Sample output of the above code-
Enter a list element separated by space 12 10 32 11 43 Sum of all elements in the list = 108 Enter a list element separated by space 200 122 422 123 Sum of all elements in the list = 867Method 2: Using While loop
Here is the Python program to find the sum of all the elements in a list using a while loop. This is almost the same as the above. We just mention the elements of the list and replace the for loop with a while loop.
Sample output of the above code-
Enter a list element separated by space 23 89 43 24 78 Sum of all elements in the list = 257 Enter a list element separated by space 45 33 78 29 66 20 Sum of all elements in the list = 271Method 3: Using sum() method
Python provides an in-built method sum(), to add all the elements in a list. The syntax of the sum() method is-
sum(iterable, start)Here, the iterable can be a list, tuples, or dictionaries. It should be numbers. The start is an optional parameter. It is added to the sum of the numbers in the iterable. The default value is zero. In the given example, we mention the elements of the list and sum them all quite easily using the sum() method-
Output of the above code -
need an explanation for this answer? contact us directly to get an explanation for this answerSum of all elements in the list = 205