Home > Software engineering >  Python | Nested loops | Sum of Sublists
Python | Nested loops | Sum of Sublists

Time:05-18

My goal with this is to generate the sum of each sublist separately using nested loops

This is my list called sales_data

sales_data = [[12, 17, 22], [2, 10, 3], [5, 12, 13]]

The sublist can be represented by any variable but for the purpose of this exercise, we will call it scoops_sold, which I have set to 0

scoops_sold = 0

So far I am able to run the nested loop as follows

sales_data = [[12, 17, 22], [2, 10, 3], [5, 12, 13]]
scoops_sold = 0

for location in sales_data:
  for element in location:
    scoops_sold  = element
print(scoops_sold)

This gives me 96 as the result

What I essentially want to accomplish is to return the sum of each sublist but I am not sure I might be able to do that. I thought about using slicing but that was not effective

CodePudding user response:

You can easily solve it using sum():

print(list(map(sum, sales_data)))

If you insist on loops:

sums = []
for location in sales_data:
  sold = 0
  for element in location:
    sold  = element
  sums.append(sold)
print(sums)

CodePudding user response:

How about

[sum(sub_list) for sub_list in sales_data]
# [51, 15, 30]

However, the question is a bit confusing because you are setting scoops_sold to 0, an int, when the result you describe is a list of int.

CodePudding user response:

If you want to have the sum of all subsets, you might want to use a list to store each subsets' sum, and by using the built-in python function sum, you just need to use one loop:

    scoops_sold = []
    for sale_data in sales_data:
        salscoops_solds_sum.append(sum(sale_data))

The same result can be achieved in one line by using list comprehensions:

scoops_sold = [sum(sale_data) for sale_data in sales_data]
  • Related