Start learning free

LESSON 254 OF 673 · NESTED LOOPS OVER GRIDS

Grid Sum in Python: Nested Loops Over a List of Lists

Practice Read the full explanation

Given a grid of integers grid, return the sum of all the numbers in it.

A grid is a table of numbers made of rows. Every row has the same number of values, one in each column. Rows are counted from the top and columns from the left, both starting at 0.

 

Example 1:

Input: grid = [[1, 2, 3],
               [4, 5, 6]]
Output: 21
Explanation: The first row adds up to 1 + 2 + 3 = 6 and the second to 4 + 5 + 6 = 15. Together: 6 + 15 = 21.

Example 2:

Input: grid = [[-3, 4],
               [5, -6]]
Output: 0
Explanation: -3 + 4 + 5 + (-6) = 0. Negative numbers make the sum smaller.

Example 3:

Input: grid = [[7]]
Output: 7
Explanation: A grid with one row and one column holds a single number.

 

Constraints:

  • grid has at least 1 row and at most 10 rows.
  • Every row has the same number of values, at least 1 and at most 10.
  • Every value is an integer between -1000 and 1000.
STEP 1 OF 5
    Ctrl + Enter to check

    PYTHON · NESTED LOOPS OVER GRIDS

    Grid Sum in Python, explained

    Problem overview

    The method gridSum receives grid, a table of integers stored as a list of rows, where each row is itself a list. It returns the sum of every number in the table. Rows are counted from the top and columns from the left, both starting at 0, and every row has the same number of values.

    For [[1, 2, 3], [4, 5, 6]] the first row adds up to 6 and the second to 15, so the answer is 21. For [[-3, 4], [5, -6]] the answer is 0, because negative numbers simply make the sum smaller. A grid with one cell, [[7]], gives 7.

    Approach: one loop per level

    A grid has two levels. The outer list holds rows, and each row holds numbers. Visiting every number therefore takes two loops, one inside the other. The outer loop picks a row; the inner loop goes through that row's values before the outer loop moves on. Together the loops visit every cell exactly once, and each value is added to a running total.

    You never need to know how many rows or columns there are. Looping directly over the items, rather than over indexes, lets Python handle the sizes.

    Step by step

    1. Create total and set it to 0. No number has been added yet.
    2. Loop row over grid. Each item of grid is a list of integers, so row is a whole row.
    3. Inside it, loop value over row. For every row, this inner loop visits all its values.
    4. Add value to total in the inner loop body.
    5. Return total after both loops. Returning inside a loop would stop after the first value or the first row.

    The solution in Python

    class Solution:
        def gridSum(self, grid: List[List[int]]) -> int:
            total = 0
            for row in grid:
                for value in row:
                    total += value
            return total
    

    Python details:

    • Indentation shows nesting. The line total += value is indented under the inner for, which is indented under the outer one. Moving the return to the same indentation as for row puts it after both loops.
    • total += value is shorthand for total = total + value.
    • Integers don't overflow. Python integers grow as needed, so a big sum is not a concern here (the values are small anyway).

    Python offers shorter forms once the loops are clear. sum(map(sum, grid)) sums each row and then the row sums, and for [[1, 2, 3], [4, 5, 6]] it also gives 21. The nested loop spells out what those calls do.

    Edge cases and common mistakes

    • Resetting total in the wrong place. If total = 0 were inside the outer loop, it would restart for every row and the function would return only the last row's sum.
    • Returning too early. A return inside the inner loop gives the first value; inside the outer loop it gives the first row's sum.
    • Looping over the wrong thing. for value in grid gives rows, not numbers, and adding a list to an integer raises a TypeError.
    • Single cell and negatives. [[7]] works with no special case, and negative values are added like any others.

    Testing

    • [[1, 2, 3], [4, 5, 6]] gives 21.
    • [[-3, 4], [5, -6]] gives 0.
    • [[7]] gives 7.
    Keep going with Python650+ step-by-step lessons, from your first line of code to coding interviews. Free to start.
    Start learning free