Editor

Diagonal Sums

Advanced · Stretch · from Python Comprehensions: List, Dict, Set, and Generator in One Guide

From the lesson: Python Comprehensions: List, Dict, Set, and Generator in One Guide

Imagine you have a list of 100 numbers and you want a new list containing only the even ones, each doubled. With a regular loop, that takes four lines. With a Python comprehension, it takes one.

Read the lesson

A grid is a list of rows, all the same length, but it does not have to be square. Number the diagonals by adding the row and the column: the cell in row r, column c lies on diagonal r + c. Write a function diagonal_sums(grid) that returns the sum of each diagonal, from diagonal 0 (the top-left cell) to the last one (the bottom-right cell).

grid = [[1, 2, 3],
        [4, 5, 6],
        [7, 8, 9]]
diagonal_sums(grid)   # [1, 6, 15, 14, 9]

Here 6 is 2 + 4, and 15 is 3 + 5 + 7. An empty grid has no diagonals. Try to build the answer with comprehensions.

Return the answer instead of printing it: Check calls diagonal_sums() with its own grids, some of them hidden.

def diagonal_sums(grid):
pass
Solution unlocks after your first Check

What Check runs

Your code runs first, then each of these lines, and 5 more that stay hidden. The output must match exactly.

RunsExpected output
diagonal_sums([[1, 2, 3], [4, 5, 6], [7, 8, 9]])[1, 6, 15, 14, 9]
diagonal_sums([[1, 2], [3, 4]])[1, 5, 4]

More List Comprehension exercises

All Python exercises · 50 practice problems · Data Structures quiz