DoAssignment study guide

A2.3 · Use nested structures for totals, extrema, and search

Learn to use nested structures for totals, extrema, and search through clear examples and targeted practice.

Ontario Grade 11 Computer Science

Programming Concepts and Skills

ICS3U study topic A2.3

A nested structure is one structure placed inside another. A list of lists, for example, stores values in rows. A loop inside another loop can visit each row and then each value in that row. This pattern can be used to calculate a total, find an extreme (the greatest or least value), or search for a target. The examples use Python 3. Python list indexes start at 0, and other classroom languages may use different syntax or indexing. The code is shown as text; each result is derived by tracing the stated input, not by claiming the code was run.

What you will learn

  • Explain how a nested structure can organize values and how nested loops visit them.
  • Trace updates to a total or greatest or least value as values are visited.
  • Use a nested loop and a flag to search nested data for a target.

1. Understand the nested structure and its input

Consider the nested list `[[4, 7], [2, 6]]`. The outer list contains two inner lists, which we can call rows. The first row has index 0 and the second row has index 1. In Python 3, `data[r][c]` selects the value at position `c` in row `r`. Thus `data[1][0]` is 2: row 1, position 0.
For a total or an extreme, the input is the nested list of values. For a search, the inputs are the nested list and a target value to look for. The outer loop selects each row in turn. The inner loop visits each value in that row before the outer loop moves on. In the examples here, this visits all values in row order.
The important relationship is that the per-value work belongs in the inner loop. When the inner loop handles a value, the program can add it, compare it with the stored extreme, or compare it with the search target. After the loops have visited the data, the stored result is ready to report.
  • An outer list can contain inner lists, each holding values.
  • The outer loop visits rows; the inner loop visits values within a row.
  • Python 3 indexes start at 0; another classroom language may differ.

2. Build a total and find an extreme

A running total is a stored sum that changes as values are processed. Start it at 0. Each visited value is added to the total inside the inner loop. For values 3, 5, 2, and 4, the total changes from 0 to 3, then 8, then 10, and finally 14. Each input value contributes once.
An extreme is either the greatest or the least value in the data. For a greatest-value search, initialize the stored value from an actual item in the input. For each visited value, compare it with the stored value and replace the stored value only if the new value is greater. For a least-value search, replace it only if the new value is smaller. The input needs at least one value so there is an actual item to use for initialization.
Initializing from an input item is useful even when all values are negative. Starting a greatest-value search at 0 could give an incorrect result if every input value is below 0. Starting from an actual value avoids that problem. In either task, a comparison justifies whether the stored extreme changes.
Tnew=Told+vT_{\text{new}}=T_{\text{old}}+v
  • Start a running total at 0 and add each visited value inside the inner loop.
  • For a greatest or least value, initialize from an actual item in non-empty data.
  • Replace the stored extreme only when the comparison shows a more extreme value.

3. Search nested data and trace the result

To search for a target, begin with a Boolean flag named `found` set to `False`. A Boolean value is either `True` or `False`. Compare every visited value with the target inside the inner loop. If a value matches, set `found` to `True`. After all rows have been checked, the flag tells whether the target appeared; this method reports whether there was a match, not its position.
Trace the flag as well as the current value. Before any match, the flag is `False`. Once a match is found, setting it to `True` records that fact. Later non-matching values do not erase the match, so the flag remains `True`.
A trace table helps make the process visible: record the value visited and the stored result before and after the update. For a total, those stored values are the running sums. For a greatest value, they are the current candidates. For a search, they are the flag values. This makes it possible to check how the final output follows from the input.
  • Start a search flag at `False`.
  • Compare every visited value with the target inside the inner loop.
  • The final flag is `True` if a match was visited and `False` if none was visited.

4. Apply the pattern carefully

Before tracing, identify the input and the result the program must produce. For a total, write down the starting value 0. For an extreme, select an actual first item as the starting candidate. For a search, write down the target and set the starting flag to `False`. Then follow the loop order one value at a time.
The position of an update matters. If adding, comparing, or checking for a match happens only once per row, some values may be missed. Place the operation inside the inner loop so it occurs for each value. Also distinguish Python assignment, written with `=`, from comparison for equality, written with `==`.
Use a trace to verify the reported result. A total should include every input value once. A greatest or least value should be one of the input values and should not be exceeded or undercut in the relevant direction. A search flag should become `True` only if a visited value equals the target.
  • Set up the stored result according to the task before visiting values.
  • Keep per-value work inside the inner loop.
  • Check the final result against the values and the task.

Trace of the running total and greatest-value candidate

TaskValue visitedStored value beforeStored value after
Total303
Total538
Total2810
Total41014
Greatest888
Greatest388
Greatest688
Greatest11811

Worked example

Total all values

Input: `[[3, 5], [2, 4]]`. Find the sum of all values.
Input values by row and position
Index → stored value[0][0]3[0][1]5[1][0]2[1][1]4

Python 3 row and position indexes are zero-based.

Python 3

values = [[3, 5], [2, 4]]
total = 0
for row in values:
    for value in row:
        total += value
print(total)
  1. Identify the input and starting state
    The input contains four values in two rows. The code starts `total` at 0, then adds each value as the inner loop visits it.
    T=0T=0
  2. Trace the updates
    The visit order is 3, 5, 2, then 4. Add each value to the previous total; the last stored total is the output.
    0+3+5+2+4=140+3+5+2+4=14
Answer: The total is 14.
Check: The four input values are each included once: 3, 5, 2, and 4.

Worked example

Find the greatest value

Input: `[[8, 3], [6, 11]]`. Find the greatest value.
Values considered for the greatest
Index → stored value[0][0]8[0][1]3[1][0]6[1][1]11

The nested loops visit each row and position in order.

Python 3

values = [[8, 3], [6, 11]]
largest = values[0][0]
for row in values:
    for value in row:
        if value > largest:
            largest = value
print(largest)
  1. Choose an initial candidate
    The input is non-empty, so initialize `largest` from its first value, 8. This ensures the candidate is an actual input value.
    L=8L=8
  2. Compare each visited value
    The loop visits 8, 3, 6, and 11. The values 3 and 6 do not replace 8. When 11 is visited, it is greater than the stored candidate, so the candidate becomes 11.
    8→8→8→118\rightarrow8\rightarrow8\rightarrow11
Answer: The greatest value is 11.
Check: The input values are 8, 3, 6, and 11; none is greater than 11.

Worked example

Search for a target

Input: `[[12, 7], [9, 15]]`; target: 9. Determine whether the target appears.
Values checked in the search
Index → stored value[0][0]12[0][1]7[1][0]9 (target)[1][1]15

The target is at Python row index 1 and position index 0.

Python 3

values = [[12, 7], [9, 15]]
target = 9
found = False
for row in values:
    for value in row:
        if value == target:
            found = True
print(found)
  1. Start with no match recorded
    The inputs are the nested list and target 9. Set `found` to `False`, then compare each value visited by the inner loop with the target.
  2. Record the match
    The first two values, 12 and 7, do not match. The value 9 at row index 1 and position index 0 matches, so `found` changes to `True`. The final value 15 does not change the flag.
    False→False→True→True\mathrm{False}\rightarrow\mathrm{False}\rightarrow\mathrm{True}\rightarrow\mathrm{True}
Answer: The target appears, so the search result is `True`.
Check: Using Python's zero-based indexes, the matching 9 is at row 1, position 0.

Common mistakes and how to avoid them

Updating the total or extreme only once per row.
Correction: Put the per-value update inside the inner loop so each value is handled.
Starting the greatest value at 0 even though all input values might be negative.
Correction: For non-empty data, initialize from an actual input item.
Checking only one row during a search.
Correction: Use the nested loops to visit and check values in every row.
Using `=` when comparing a value to the target in Python.
Correction: Use `==` for equality comparison and `=` for assignment.

Lesson summary

  • Nested lists can organize values into rows, and nested loops can visit them row by row.
  • For a total, start at 0 and add each visited value.
  • For a greatest or least value, initialize from an actual item and update after comparison.
  • For a search, compare each visited value with the target and track whether any match occurs.

Check your understanding

Question 1

A nested list contains `[[2, 1], [5, 3]]`. What is the total of all values?
  1. 8
  2. 11
  3. 6
  4. 5
Show answer and explanation
11
Add each value once: 2+1+5+3=112+1+5+3=11.

Question 2

Which is the greatest value in `[[4, 10], [6, 7]]`?
  1. 4
  2. 7
  3. 10
  4. 27
Show answer and explanation
10
Comparing 4, 10, 6, and 7 shows that 10 is greatest.

Question 3

A search checks for target 6 in `[[1, 2], [6, 4]]`. What is the final `found` flag?
  1. `False`
  2. `True`
  3. 6
  4. The number of rows
Show answer and explanation
`True`
The value 6 appears in the second row, so the flag becomes and remains `True`.

Key terms

Nested structure
A structure inside another structure, such as a list of lists or a loop inside another loop.
Running total
A stored sum updated as each value is processed.
Extreme
The greatest or least value among the values considered.
Target
The value a search checks for.

Continue through ICS3U

View the complete ICS3U Ontario Grade 11 Computer Science curriculum and lessons

Tutor support for A2.3 · Use nested structures for totals, extrema, and search

Working on A2.3 · Use nested structures for totals, extrema, and search in ICS3U? Bring the question and your own attempt. In a live session, you can trace a small example and find the first step where the output differs from what you expected. Ask about the first step that does not make sense, then try a similar question yourself.

Explore coding tutoring · Request an eligible free 30-minute introduction. Your request is matched by subject and language; a tutor must accept before a time is confirmed.

برای مبحث A2.3 · کاربرد ساختارهای تودرتو برای جمع، بیشینه و جست‌وجو در درس ICS3U، سؤال و تلاش خود را همراه بیاورید. در جلسه می‌توانید یک مثال کوچک را دنبال کنید و نخستین گامی را که خروجی با انتظار شما فرق دارد پیدا کنید. راهنمای معلم برنامه‌نویسی را ببینید یا جلسهٔ معارفهٔ رایگان ۳۰ دقیقه‌ای درخواست کنید. زمان جلسه پس از پذیرش معلم قطعی می‌شود.

About this lesson and its review

Published by DoAssignment. This reviewed lesson follows Ontario Grade 11 Computer Science (ICS3U), expectation A2.3. It is a study resource, not an official curriculum publication.

Before publication, content is checked for structure, mathematical or chemical notation, calculations, course boundaries, and readability. Errors can still occur, so corrections are welcomed.

Official curriculum reference

Report a correction or ask a question