Walking a table
After this: Put a loop inside a loop to add up a whole table, one row at a time, or one column at a time.
On this page · 6 sections · 4 checks
The teacher wants the total of every mark in the mark book. On paper you would go along the first row adding as you go, then along the second row, and so on. One row at a time, every value in each row. That is a loop inside a loop, and you wrote one in "Repeating": the outer loop picked a row of seats and the inner loop went along it. Here the rows are real lists.
The grand total
The plan has the three parts from "Lists": a box before the loop, a change inside, a print after. What is new is that the inside is itself a loop.
totalstarts at 0.- The outer loop picks the first row,
[1, 2, 3]. The inner loop goes along it:totalbecomes 1, then 3, then 6. - The outer loop picks the second row,
[4, 5, 6]. The inner loop starts again:totalbecomes 10, then 15, then 21. - Both loops are finished. 21 is printed.
- Run the programRun it and watch the box total. It should change six times, once for each value, while row changes only twice.
grid = [[1, 2, 3], [4, 5, 6]]total = 0for row in grid: for value in row: total = total + valueprint(total)run the program to see its boxes
nothing printed yetPress Run it, then step through the program one line at a time.
- lines
- 0
- prints
- 0
- calls
- 0
Watch the two boxes. row changes twice, once per row. value changes six times, once per value, because the inner loop runs through the whole row before the outer loop moves on. The inner box changes fastest, as it did in "Repeating". The line in the middle, total = total + valuetotal = total + value;, runs six times, which is the number of rows times the number of columns.
Python runs in the browser below; Java is traced above.
Add a third row and run again; the total should rise by that row's values.
One total per row
Sometimes you want each row's own total: one number per student. The only change is where total starts and where it is printed. Put both inside the outer loop, and total starts again at 0 for each row and is printed when that row is done.
grid = [[1, 2, 3], [4, 5, 6]]for row in grid: total = 0 for value in row: total = total + value print(total)run the program to see its boxes
nothing printed yetPress Run it, then step through the program one line at a time.
- lines
- 0
- prints
- 0
- calls
- 0
Two rows, two printed lines: 6 and 15. Compare the two programs line by line. The loops are the same; the box moved inside the outer loop.
One total per column
A column is not a list of its own; its values are spread over the rows, one in each. To add up column 1, read position 1 of every row. So the outer loop picks a column number, and the inner loop goes through the rows reading that position.
grid = [[1, 2, 3], [4, 5, 6]]for col in range(len(grid[0])): total = 0 for row in grid: total = total + row[col] print(total)5 7 9
int[][] grid = {{1, 2, 3}, {4, 5, 6}};for (int col = 0; col < grid[0].length; col++) { int total = 0; for (int[] row : grid) { total = total + row[col]; } System.out.println(total);}5 7 9
Column 0 holds 1 and 4, total 5. Column 1 holds 2 and 5, total 7. Column 2 holds 3 and 6, total 9. The outer loop is the counting loop from "Repeating", running from 0 up to the number of columns, which is the length of one row. The inner loop reads row[col]: the same position in each row.
The rule for all three programs: the outer loop decides what one pass of the inner loop covers. Over a row, over a column, or over everything.
Every pair from one list
Two loops can also run over one flat list, to look at every pair of values. From [1, 2, 3] the pairs are 1 and 2, 1 and 3, and 2 and 3: three pairs, each with the first value before the second. The outer loop picks a position i; the inner loop runs j from i + 1 to the end, so that no value is paired with itself and no pair appears twice.
nums = [1, 2, 3]for i in range(len(nums)): for j in range(i + 1, len(nums)): print(nums[i], nums[j])run the program to see its boxes
nothing printed yetPress Run it, then step through the program one line at a time.
- lines
- 0
- prints
- 0
- calls
- 0
Three printed lines. With four values there would be six pairs, and with ten values forty-five. This shape comes back often: comparing every value with every later value is how you find, for example, the two closest values in a list.
Check yourself
The walk runs over [[1, 2, 3], [4, 5, 6]]{{1, 2, 3}, {4, 5, 6}} with total starting at 0 before both loops. What is printed after the loops?
In the walk, right after the inner line total = total + valuetotal = total + value; has run for the fourth time, what do row, value and total hold?
grid = [[1, 2, 3], [4, 5, 6]]total = 0for row in grid: for value in row: total = total + valueprint(total)int[][] grid = {{1, 2, 3}, {4, 5, 6}};int total = 0;for (int[] row : grid) { for (int value : row) { total = total + value; }}System.out.println(total);Complete the missing line so that the inner loop goes through the values of the current row and the program prints 21. Write the whole line, including the colon at the endbrackets and the opening brace.
grid = [[1, 2, 3], [4, 5, 6]]total = 0for row in grid: ____________________ # ← one pass for each value in this row total = total + valueprint(total)int[][] grid = {{1, 2, 3}, {4, 5, 6}};int total = 0;for (int[] row : grid) { ____________________ // ← one pass for each value in this row total = total + value; }}System.out.println(total);The pairs program is run on three even numbers. What does it print?
nums = [2, 4, 6]for i in range(len(nums)): for j in range(i + 1, len(nums)): print(nums[i], nums[j])int[] nums = {2, 4, 6};for (int i = 0; i < nums.length; i++) { for (int j = i + 1; j < nums.length; j++) { System.out.println(nums[i] + " " + nums[j]); }}Honesty notes
- Visit every value of a table with a loop inside a loop: the outer loop picks a row, the inner loop goes along it.
- Put the running total before both loops for the grand total, or inside the outer loop for one total per row.
- Add up a column by looping over the rows and reading the same position in each one.
- Make every pair from one list with two counting loops, where the inner one starts one past the outer one.