[Python][Coding Pattern] Row Sums

Row Sums

We need to return the sum of each row from a given 2D list (a list of lists of integers).

Each row is a list of integers — the result should be a flat list of row totals.

Key Insight

Each row in the matrix is simply one of the inner lists in the outer list.

We can pass each of them directly to the sum() function to compute their total.

Step-by-step Logic

1. Use list comprehension

Use a list comprehension to build a new list from the matrix.

2. Loop through the outer list

Each iteration of the loop extracts one inner list — which represents a single row.

3. Apply sum() to each row

The sum() function takes each row and returns the total of its elements.

4. Return the list comprehension

The final list is a collection of row sums.

Functions and Concepts

  • sum() : adds up all numbers in an iterable
  • list comprehension :one-liner loop for creating new lists

# Write a function that receives a 2D list of integers and returns a list containing the sum of each row.

# Constraints:
# Each inner list contains integers
# Return an empty list if the input is empty
# Must work with irregular row lengths

# Signature:
def row_sums(matrix: list[list[int]]) -> list[int]:
    return [sum(row) for row in matrix]


if __name__ == '__main__':
    assert row_sums([[1, 2, 3], [4, 5], [6]]) == [6, 9, 6], 'test 1 failed'
    assert row_sums([]) == [], 'test 2 failed'

Comments