0

we aren't allowed to import any functions or outside stuff, but just using nested loops only.

So I have a list that's something like this:

table = [[1,2,3],
         [2,3,4],
         [3,4,5]]

etc. And I'm writing a function that sums up each column. This is what I have so far:

def sum_column(table):
    list1 = []
    for each in table:
        for item in each:
            list1.append(item)
        for i in range(len(list1)):
            for j in range(len(each)):
                col = (list1[j:i+1:len(each)])
    return col

what I've been trying to do is just to get each column into its own list then sum them up from there. But I realize this function only returns the j value of each term (I'm supposed to code it so it will work on a list with any number of columns) and not every term like I want it to. So I'm kinda lost right now and any help is appreciated.

Isabella H
  • 27
  • 1

1 Answers1

2

There's no need to put each column into its own list. Initialize the result list with zeroes for each column. Then loop through the rows and columns, and add to the corresponding result value.

def sum_column(table):
    result = [0] * len(table[0]): # len(table[0]) is the number of columns
    for row in table:
        for col, value in enumerate(row):
            result[col] += value
    return result
Barmar
  • 741,623
  • 53
  • 500
  • 612