1

Just doing an exercise question as follows: Take a ' number square' as a parameter and returns a list of the column sums.

e.g

square = [
[1, 2, 3, 4],
[5, 6, 7, 8],
[9, 10, 11, 12],
[13, 14, 15, 16]
]

Result should be =

[28, 32, 36, 40]

What I have so far:

def column_sums(square):
    col_list = []
    for i in range(len(square)): 
        col_sum = 0
        for j in range(len(square[i])): 
            col_sum += square[j]
        col_list.append(col_sum)
    return col_list

So I think I have all the parameters laid out, with all the indexing correct, but I am stuck because I get an error

builtins.TypeError: unsupported operand type(s) for +=: 'int' and 'list'

Which shouldn't happen if I am referencing the element within the list I thought.

Also it's probably easier to use the SUM command here, but couldn't figure out a way to use it cleanly.

Adding elements from separate lists via indexing.

2
  • Possible duplicate of Sum of nested list without using SUM function (exercise) Commented Aug 9, 2016 at 6:40
  • Change square[j] to square[i][j] that is the specific location of the square. Currently, you are typecasting a list to an integer Commented Aug 9, 2016 at 6:41

3 Answers 3

2

A more simpler solution would be to transpose the list of lists with zip and take the sum across each new sublist:

def column_sums(square):
    return [sum(i) for i in zip(*square)]

zip(*square) unpacks the list of lists and returns all items from each column (zipped as tuples) in successions.

>>> column_sums(square)
[28, 32, 36, 40]

You could also use numpy.sum to do this by setting the axis parameter to 0, meaning sum along rows (i.e. sum on each column):

>>> import numpy as np
>>> square = np.array(square)
>>> square.sum(axis=0)
array([28, 32, 36, 40])
Sign up to request clarification or add additional context in comments.

Comments

1

It should be col_sum += square[j][i] since you want to access the element at position j of the list at position i.

3 Comments

Hmm but with that addition it just gives me back the sum of each list e.g [10, 26, 42, 58] to the above statement
That gives you the row sums not the column sums
Just swap the indices to get the col sum and not the row sum
1

You should change the line of summing to:

col_sum += square[j][i]

because square[j] is the j'th row (list), but you need the current column, which is the i'th element in that row.

But here is my solution using sum and list comprehensions:

def column_sums2(square):
    def col(i):
        return [row[i] for row in square]
    return [sum(col(i)) for i in range(len(square))]

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.