In this tutorial, we will learn about the sum of numbers in a list i.e. the sum of a list in Python. There are various methods we can use to sum a list of numbers. For example – sum() is an in-built function in Python.
- Using Looping like for loop and while loop.
- Using sum() built-in function
- List Comprehension
(1) Python List Sum using For Loop
The for loop in Python is a control flow statement that is used to execute code repeatedly over a sequence like a string, list, tuple, set, range, or dictionary(dict) type.
Using range() function
Here, we will use the range() function in for loop to iterate elements in the Python list to get a sum of elements. Inside the loop, we will access each element using the index position and add each element to the total variable. The sum is stored in this variable. if you wanted to start the initial value, then assign the value you wanted to the total variable.
mylist=[2,10,12,15,25,27] total=0 for i in range(len(mylist)) : total = total + i print(“Sum : “, total)
Sum : 91
Using for loop
Here, we just use the list without the range() function. Here, we will get a value from the list for each iteration and add each element to the variable. The sum is stored in this variable.
mylist=[2,10,12,15,25,27] total=0 for i in mylist : total = total + i print(“Sum : “, total)
Sum : 91
(2) Python sum of a list using sum() function
The sum() is the built-in function in Python that is used to get or find the sum of all numeric elements from the list. By using this you can also specify an initial value to start the calculating sum.
It takes two parameters as input and returns the total sum of elements in the list. The first parameter is the input list and the second parameter specified the start value in which the sum is computed from this value. This parameter is optional.
mylist=[2,10,12,15,25,27] print(“Sum : “, sum(mylist)
Sum : 91
(3) Python Sum list using List Comprehension
Let’s have a list of integers and return the sum of all elements in the list using sum() by passing List Comprehension as a parameter. With Python list comprehension, we can create lists by specifying the elements. We select elements that we want to include, along with any conditions or operations. All this is done in a single line of code
mylist=[2,10,12,15,25,27] print(“Sum : “, sum([i for i in mylist]))
Sum : 91
We provided for loop inside the list comprehension and iterating each element in the list. So the sum() function will take each value from the list and return the total sum.
Follow for More Info – https://instagram.com/developerhelps?igshid=MzRlODBiNWFlZA==