Hi in this article let's look into how we can sum all the numbers in a list. given the list of numbers for you have to traverse all the numbers of a list get a sum of all the numbers in a list problem statement.
Now let's try to solve this assuming the given list is a single list without any nested list inside it.
Python Program to Sum All The Items in a List
Let's
take a list of numbers and try to traverse all the items present in the
list and also take a variable total while we traverse all the numbers
in a list keep adding the every number to the total variable and
finally when the For loop completes we will have the sum of list items
will be stored in total variable
my_list = [1, 2, 3, 4, 500, 5, 6, 7, 8, 9]
total = 0
for number in my_list:
total += number
print("Sum of list of numbers is : ", total)
OUTPUT :
Sum of list of numbers is : 545
Python Program to Sum All The Items in a Nested List
Now
if the given list is a nested list containing a number, let's write a
recursive function that calls itself if a nested list is found. Given a
nested list as input argument to the function, take a variable local_sum
to store the sum of the nested list.
Use the for loop to
traverse all the items present in the nested list, check if item is an
instance of list then call the function recursively. If the nested list
item is integer then add it to the local_sum.
Once the function
returns the local_sum variable. The main function print the return value
of the function as a sum of list of numbers.
def get_total(data):
local_sum = 0
for item in data:
if isinstance(item, list):
local_sum += get_total(item)
elif isinstance(item, int):
local_sum += item
return local_sum
my_list = [1, [2, 3], [4, 500, [5], 6], [7, 8, 9]]
total = get_total(my_list)
print("Sum of list of numbers is : ", total)
OUTPUT :
Sum of list of numbers is : 545
Conclusion : Try the sum of list by yourself, comment down if you ave any queries.
0 Comments