How to add all numbers in a list in Python

Hi everyone, today in this tutorial let us see how to add all numbers in a list in Python. Basically, we can add numbers in a list in many ways, like in other programming languages we can use loops(for loop, while loop). We can also use lambda.

But in our tutorial let us see how to add elements in a list using built-in function and slicing. This way of doing is better than using other methods. This is because slicing is an important technique in machine learning.

How can you add all numbers in a list in Python

Let us now see how to add all numbers in a list using a built-in function. We use sum() which is a built-in function in Python programming language.

sum()

The sum() is a built-in function as said earlier. This function will work only when numeric values are given to it, this will not work when alphabets are given to it or when numbers are given in the form of string it will show errors. This function basically sums up the numbers that are given to this and return the sum of numbers given in it.

Now, let us see the code.

p=[2,3,5]
print(sum(p))

OUTPUT:

10

Let us now see the usage of for loop in sum() function.

p=[2,3,5]
print(sum(i for i in p))

OUTPUT:

10

You can also use the sum() function to add a constant value for the sum total of the list. The syntax of the sum() function is sum(iterable, start). So here, start means a value that can be summed up to the list and iterable means list, tuple, dict, etc.,

p=[2,3,5]
print(sum(p,50))

OUTPUT:

60

Now, let us see how to add a list of numbers using the slicing method.

Slicing

This slicing is an amazing feature given to us in Python language. This way of writing the code and analyzing the data plays a key role in Machine learning and Deep learning techniques.

Let us now have a look on our code.

y=[1,7,5,6,3]
s=sum(y[0:len(y)])
print(s)

OUTPUT:

22

You may also read: