Home Tutorials How To Sum A List In Python

### How To Sum A List In Python

Write a Python program that finds the sum of all the elements in a list of numbers in Python. Here I described something new that will help you out in good ways like how you can find out sum a list in Python.

## How To Sum A List In Python

#### Example #1:

```total = 0

# creating a list

list1 = [11, 5, 17, 18, 23]

# Iterate each element in list

# and add them in variable total

for ele in range(0, len(list1)):
total = total + list1[ele]
# printing total value

print(total)
```
• So, first of all, we made a variable name is: total
• Second, we took a list randomly.
• Then arrange them in for loop in Python.
• There we also took a length function to see the total length of list.
• There just put a trick that will sum a list in Python automatically.
• Like took a variable then plus sign symbol and then assign the list variable.

Output: 74

#### Example #2 : Using while() loop

```total = 0

ele = 0

# creating a list

list1 = [11, 5, 17, 18, 23]

# Iterate each element in list

# and add them in variable total

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

# printing total value
print(total)
```
• Here we made two variables one is: the total second is ele
• So, one random list.
• Put the while loop to get the sum of the list.
• And as you know well too about length function is common to get the total length of a list.
• Then the same trick as we used above but one is also required to find sum value by value.
• Then simply, print out the total variable at the end outside the loop.

Output: 74

The first method is to use the Naive technique. The second method is to use a NumPy array.

Numpy is a read data library that can be used for a wide range of applications. It comes at a high working with these arrays objects and facilities for manipulating it. The third method is to use zip() and list comprehension.

You turn the data into a NumPy array and feed it to the np. sum() method. The axis argument of the sum function specifies which axis the sum value should be calculated along. Use axis=0 if you wish to sum across columns.

Let’s have a practice also of how to use Python Try Except that’s pretty cool.