Search code examples
pythonlistloopsdata-science

Nested list: How to sum all of the element in index 1 & 2 in these list by using for loop?


Each table row contains sales data from stores in different cities:

-The element with index 1 contains sales for the first six months. -The element with index 2 contains sales for the next six months.

Find the total sales for the year, and add the results to the end of each sublist.

sales = [
    ['New York', 105820, 112180],
    ['Los Angeles', 85899, 91021],
    ['Tampa', 35010, 32001],
    ['Washington', 37011, 39595]
]
    
# write your code here

print(sales)

I'm trying to use this code, but its results error:

for i in sales:
    i = sum(sales[1],[2])
    
print(sales)

Output: Traceback (most recent call last): File "main.py", line 9, in i = sum(sales[1],[2]) TypeError: can only concatenate list (not "str") to list


Solution

  • To calculate sum of second and third column in each row you can:

     for item in sales:
        item.append(item[1] + item[2])
    

    To calculate overall sum you can simply:

     for item in sales:
        sum = sum + item[-1]
    

    your output is like below and sum holds summation of given numbers.

     [['New York', 105820, 112180, 218000],
     ['Los Angeles', 85899, 91021, 176920],
     ['Tampa', 35010, 32001, 67011],
     ['Washington', 37011, 39595, 76606]]
    
     sum = 538537
    

    Alternative solution: you can convert sales to numpy array and use numpy methods on new array.