In this Python tutorial, we will see, how to add numbers in a list in Python without SUM.
We can add numbers in a Python list without sum by using below two methods.
- Add numbers in a list python using for loop
- add numbers in a list python using reduce() function
Add numbers in a list python using for loop
Let us see, how to add numbers in a list in Python without sum, by using for loop.
Create a function that is going to sum the numbers within the list using the below code.
def sum_list(list_num):
sum = 0
for num in list_num:
sum +=num
return sum
Create a list that contains the number of people who died in the top 5 states of the USA such as California = 96071
, Texas = 90940
, Florida = 81464
, New York = 71499
and Pennsylvania = 47213
.
usa_covid_death = [96071, 90940, 81464, 71899, 47213]
Pass the above list to sum the total number of people who died in these five states using the below code.
sum_list(usa_covid_death)
Read: How to find the sum of the list in Python
This is how to add numbers in list in Python using for loop.
Add numbers in a list python without sum by using reduce() function
Now, let us see, how to add numbers in a list python without sum by using reduce() function.
Applying a specific function to all of the list components indicated in the sequence sent along is what the reduce() function does. In the “functools” module, this function is defined.
First, import the required libraries and create a sum function using the below code.
import functools
def s_list(a,b):
return a + b
Create a list that contains the number of people who died in the top 5 states of the USA such as California = 96071
, Texas = 90940
, Florida = 81464
, New York = 71499
and Pennsylvania = 47213
.
usa_covid_death = [96071, 90940, 81464, 71899, 47213]
Pass the created function “s_list()” and the list “usa_covid_death” to sum the numbers of that using the below code.
sum = functools.reduce(s_list,usa_covid_death)
Check the sum of the numbers of the list using the below code.
print(sum)
Read: Add two numbers in Python using the function
This is how to sum the numbers in a list in python without the sum function of Python.
We have covered how to sum the elements in the list python using the loop and the reduce function but without using SUM.
You may also like:
- How to Convert NumPy Array to List in Python
- How to find smallest number in a Python list
- Python select from a list
- How to Add Elements in a Set in Python
- How to Add Elements in List in Python Using For Loop
I am Bijay Kumar, a Microsoft MVP in SharePoint. Apart from SharePoint, I started working on Python, Machine learning, and artificial intelligence for the last 5 years. During this time I got expertise in various Python libraries also like Tkinter, Pandas, NumPy, Turtle, Django, Matplotlib, Tensorflow, Scipy, Scikit-Learn, etc… for various clients in the United States, Canada, the United Kingdom, Australia, New Zealand, etc. Check out my profile.