Weeks
Computational ThinkingWeek 5 · Lists, foreach and List Functions
Week 5 Notes

Computational
Thinking 5

Lists: why we need them, how to build and combine them, walking through them with foreach, matching items across lists, the Top Students example, and the core list functions. Lectures 5.2 and 5.4, Tutorial 5.1.

5 chapters22 worked examples~35 min read
Lists++ and extendforeachNested foreachList functions

Chapters

  1. 01Introducing ListsLecture 5.2
  2. 02Worked Example: Top StudentsLecture 5.4
  3. 03Matching More Than Two ListsLecture 5.4
  4. 04Core List FunctionsTutorial 5.1
  5. 05Week 5 Summary SheetAll lectures
01
Lecture 5.2

Introducing Lists

Collections beyond single variables: list notation, ++, extend, foreach and common items.

So far every variable has held one value: a running total, a flag, the current card. This lecture introduces the first collection: the list.

1.1Why we need lists

A normal variable holds one value at a time: a running total, a flag, the current row you are reading. But many real problems ask you to keep track of a whole group of values at once:

  • Every student who scored the highest marks in Physics.
  • Every customer who bought a food item from SV Stores.
  • Every noun in a sentence that follows an adjective.

In each case you do not know in advance how many items you will collect, so a single variable cannot hold the answer. You need a collection.

A variable: one valuetotal62holds 62A list: many values, one namemayList[124...]student1, student2, student3 ... not needed
Figure 1. One variable holds one value; one list name refers to a whole sequence
Definition: list

The simplest kind of collection is a list: a sequence of values, referred to by one variable name. Instead of juggling student1, student2, student3 ..., you keep a single variable, say mayList, that refers to the entire sequence.

1.2Writing a list

A list is written as values inside square brackets, separated by commas:

list-literals.pseudo
[1, 13, 2]
["Vedanayagam", "cane", "Monday", "school"]
[]  // an empty list — perfectly valid, has zero items
Key idea

A list can hold numbers, strings, or any other kind of value, and the empty list [] is your starting point whenever you are about to build one up.

  • [1, 13, 2]: three numbers, so 3 items.
  • The second list holds four strings (Vedanayagam, cane, Monday, school), so 4 items.
  • []: nothing, so 0 items.
Order and repeats (extra). A list is a sequence: the order of the items matters and the same value may appear more than once. [1, 13, 2] and [2, 13, 1] are different lists, and [2, 17, 1, 1] holds 1 twice.

1.3Combining lists: ++

Two lists can be joined end to end using ++. This is called append. Every item from the first list comes first, then every item from the second.

l1[113]++l2[2171][1132171]first all of l1then all of l2
Figure 2. l1 ++ l2: the items of l1, then the items of l2
ExampleIf l1 = [1, 13] and l2 = [2, 17, 1], then l1 ++ l2 gives [1, 13, 2, 17, 1].
  • Order matters (extra). l2 ++ l1 gives [2, 17, 1, 1, 13], a different list.
  • Lengths add up. The result has 2 + 3 = 5 items; nothing is removed, even repeated values.
  • Both sides are lists. ++ joins a list with a list, never a list with a single value.

1.4Growing a list: extend

The most common thing you will do with a list is add one new item to the end. Since ++ joins two lists, you add a single item x by wrapping it in its own one-item list and appending that:

extend.pseudo
l = l ++ [x]  // extends l with item x
l =[58]++[x]the list so farx wrapped in its own one-item list[58x]the new l
Figure 3. Wrap x as [x], then append: l = l ++ [x]
Think of it as

"Take the list so far, and glue on one more box containing x." The square brackets around x are what make it a list, so that ++ can join it.

1.5Building a list while scanning a table

A very common pattern: scan every row of a table, and whenever a row matches some condition, append it to a list. Start with an empty list, then extend it row by row.

Example: students born in MayScan Table 1 row by row. Whenever a row's month of birth is May, append that student's sequence number to mayList.
may-list.pseudo
mayList = []
while (Table 1 has more rows) {
    Read the first row X in Table 1
    if (X.MonthOfBirth == "May") {
        mayList = mayList ++ [X.Seqno]
    }
    Move X to Table 2
}

The same pattern, with a different condition, gives you the students from Chennai:

chennai-list.pseudo
chennaiList = []
while (Table 1 has more rows) {
    Read the first row X in Table 1
    if (X.TownCity == "Chennai") {
        chennaiList = chennaiList ++ [X.Seqno]
    }
    Move X to Table 2
}

Here is the May loop run on six illustrative rows (they are not lecture data; they only show how the list grows):

Table 1 (illustrative rows)SeqnoMonthCitymayList after each row0NovErode[]1MaySalem[1]2MayChennai[12]3JulChennai[12]4MayChennai[124]5FebMadurai[124]
Figure 4. Each May row appends its Seqno; other rows leave mayList unchanged (illustrative rows)
Row readMonthOfBirthConditionmayList after the row
0NovFalse[]
1MayTrue[1]
2MayTrue[1, 2]
3JulFalse[1, 2]
4MayTrue[1, 2, 4]
5FebFalse[1, 2, 4]

On the same six rows, the Chennai loop gives chennaiList = [2, 3, 4].

Why the Seqno and not the whole row? The sequence number identifies a student uniquely, so it is enough to remember who matched. Later, two lists of Seqnos can be compared item by item to find students in both.

1.6Iterating with foreach

Once you have a list, you will usually want to look at every item in it and do something with each one. That is exactly what foreach is for: it walks through the list, one item at a time, and the loop variable takes on each value in turn.

foreach.pseudo
foreach x in l {
    Do something with x
}
l[2030405010]pass 1x = 20pass 2x = 30pass 3x = 40pass 4x = 50pass 5x = 10x takes each value in turn, from first to last
Figure 5. foreach x in l: one pass per item, in order
while over a tableforeach over a list
Walks throughrows of a tableitems of a list
Current elementRead the first row Xthe loop variable x
Moving onMove X to Table 2 (by hand)automatic
Stopswhen Table 1 has no more rowsafter the last item
Comparison (extra). The table above is a reading aid, not a slide. The point is that foreach needs no "move to the other pile" step and leaves the list as it was.

1.7Finding items common to two lists

To find students who satisfy two conditions at once, say born in May and from Chennai, you compare every item of one list against every item of the other. That means a foreach inside a foreach: for each item in the first list, scan the whole second list looking for a match.

may-chennai.pseudo
mayChennaiList = []
foreach x in mayList {
    foreach y in chennaiList {
        if (x == y) {
            mayChennaiList = mayChennaiList ++ [x]
        }
    }
}
chennaiList (inner loop: y)234mayList(outer loop: x)1✗✗✗2✓✗✗4✗✗✓3 × 3 = 9 comparisonsmayChennaiList[24]
Figure 6. Every x of mayList is compared with every y of chennaiList; matches are kept
Key idea

Nested foreach is how you check "is this item in the other list too?". The outer loop picks a candidate, the inner loop searches for it.

  1. Outer x = 1: compare with 2, 3, 4. No match.
  2. Outer x = 2: compare with 2 (match, append 2), 3, 4.
  3. Outer x = 4: compare with 2, 3, 4 (match, append 4).
  4. Result: mayChennaiList = [2, 4] after 3 × 3 = 9 comparisons.
Counting the work (extra). The inner loop runs completely for every outer item, so lists of sizes m and n need m × n comparisons of x == y. This is the nested iteration of Week 4, between two lists.

1.8Summary of the lecture

  • A list is a sequence [x1, x2, ..., xn].
  • Combine lists with ++.
  • Grow a list by one item: l = l ++ [x].
  • foreach x in l { ... } walks through every value in l.

1.9Going deeper

  • Why not one variable per student? (extra) You would need to know the number of variables before scanning. A list grows to whatever size the data needs.
  • The result keeps the outer list's order (extra). mayChennaiList lists matches in the order they appear in mayList.
  • Repeats repeat (extra). If a value appears twice in either list, the nested loop appends it more than once: matching [3, 3, 5] with [3, 5, 5] gives [3, 3, 5, 5]. Seqnos are unique, so this does not happen in the lecture.
  • Two conditions in one loop (extra). For a single table, one scan whose if joins X.MonthOfBirth == "May" and X.TownCity == "Chennai" with and also works. Matching lists is the general tool when the lists come from different scans or different procedures.

1.10Exam tips and common mistakes

Exam tips
  • Start every list you build with [], before the loop.
  • For a nested foreach, count the comparisons as (outer length) × (inner length).
  • When tracing ++, write the left list first, then the right one, keeping repeats.
Common mistakes
  • Writing l = l ++ x: x must be wrapped as [x].
  • Thinking l1 ++ l2 equals l2 ++ l1.
  • Initialising the list inside the loop, which empties it on every row.
  • Stopping the inner loop at the first item instead of scanning the whole second list.

Practice questions (graded-assignment style)

Q1Length after ++

Numerical Answer Type (NAT).

If l1 = [1, 13] and l2 = [2, 17, 1], how many items does l1 ++ l2 have?

Solution
Idea

Append keeps every item of both lists.

  • [1, 13, 2, 17, 1] has 2 + 3 items.
  • Answer: 5
Q2Adding one item

Multiple Choice Question (MCQ): choose the one correct option.

Which statement adds the item 7 to the end of list l?

1
l = l ++ 7
2
l = l ++ [7]
3
l = [7] ++ l
4
l = [l] ++ [7]
Solution
Idea

++ joins two lists, so 7 must become a list.

  • l ++ 7 joins a list with a number, which is not allowed.
  • [7] ++ l puts 7 at the front.
  • Answer: option 2.
Q3Order of ++

Multiple Choice Question (MCQ): choose the one correct option.

With l1 = [1, 13] and l2 = [2, 17, 1], what is l2 ++ l1?

1
[1, 13, 2, 17, 1]
2
[1, 2, 13, 17]
3
[2, 17, 1, 1, 13]
4
[2, 17, 1, 13]
Solution
Idea

The left list comes first.

  • The items of l2, then the items of l1: [2, 17, 1, 1, 13].
  • Answer: option 3.
Q4Filtering into a list

Numerical Answer Type (NAT).

What is the length of l after this code runs?

question.pseudo
l = []
foreach x in [3, 8, 5, 8] {
    if (x > 4) {
        l = l ++ [x]
    }
}
Solution
Idea

Append only the items greater than 4.

  • 8 is appended, 3 is skipped, 5 is appended, the second 8 is appended again.
  • l = [8, 5, 8].
  • Answer: 3
Q5Counting comparisons

Numerical Answer Type (NAT).

mayList has 4 items and chennaiList has 5. How many times is x == y checked by the nested foreach?

Solution
Idea

The inner loop runs fully for every outer item.

  • 4 × 5 = 20.
  • Answer: 20
Q6List facts

Multiple Select Question (MSQ): select all that apply.

Choose the correct statements.

1
[] is a valid list with zero items
2
A list can hold strings
3
l1 ++ l2 is always equal to l2 ++ l1
4
foreach visits every item of the list once, in order
Solution
Idea

Recall what a list and foreach are.

  • 1, 2 and 4 are true. ++ is not commutative (statement 3): order matters.
  • Answer: options 1, 2 and 4.
Revision overview
Why listsOne variable, one value
Unknown number of items
One name, whole sequence
Writing lists[1, 13, 2]
Strings allowed
[] is the empty list
Append ++[1, 13] ++ [2, 17, 1]
= [1, 13, 2, 17, 1]
Order matters
ListsLecture 5.2
Extendl = l ++ [x]
Start from []
Append matching rows
foreachforeach x in l
x takes each value
No Move step needed
Common itemsforeach inside foreach
Keep x when x == y
m × n comparisons
Revision: what a list is, how to build one and how to walk through it
Next · Lecture 5.4Worked Example: Top Students
02
Lecture 5.4

Worked Example: Top Students

Combining lists across subjects: a cutoff per subject, a list per subject, then matching.

This lecture puts lists to work on a full problem, built from a procedure you have seen before plus the list patterns of Lecture 5.2.

2.1The problem

We want to find students who are doing well across all subjects: specifically, students who rank among the top 3 marks in each of Mathematics, Physics and Chemistry. To do that we first need a way to find the cutoff mark (the third-highest score) in a single subject.

Step 2Step 3Step 4Step 5MathscutoffmathsListPhysicscutoffphysListChemistrycutoffchemListmathsPhysListmathsPhysChemListtoppers in all threemark ≥ cutoff?cutoff = TopThreeMarks(…)nested foreach
Figure 7. The plan: a cutoff per subject, a list per subject, then two rounds of matching

2.2Step 1: finding the third-highest mark

This procedure scans the whole table once, keeping running track of the highest, second-highest and third-highest marks seen so far for one subject. Whenever a new mark beats one of these, everything below it shifts down a rank.

TopThreeMarks.pseudo
Procedure TopThreeMarks(Subj)
    max = 0, secondmax = 0, thirdmax = 0
    while (Table 1 has more rows) {
        Read the first row X in Table 1
        if (X.Subj > max) {
            thirdmax = secondmax
            secondmax = max
            max = X.Subj
        }
        if (max > X.Subj and X.Subj > secondmax) {
            thirdmax = secondmax
            secondmax = X.Subj
        }
        if (secondmax > X.Subj and X.Subj > thirdmax) {
            thirdmax = X.Subj
        }
        Move X to Table 2
    }
    return(thirdmax)
End TopThreeMarks
Why this works

Only one of the three if blocks ever fires for a given row. Once a mark updates max, it now equals max, so the "is it below max" check of the next block is automatically false. The three checks quietly hand off to each other instead of double-counting a mark.

Same procedure as Week 3. Week 3 wrote the middle test as max > X.Subj > secondmax; here it is written as two tests joined by and: max > X.Subj and X.Subj > secondmax. Both mean "strictly between". This version also reads rows from Table 1 and moves them to Table 2, as tables do in this course.

2.3Trace: marks 30, 20, 50, 10, 40

max2nd3rdfiredmark: 303000if 1mark: 2030200if 2mark: 50503020if 1mark: 10503020nonemark: 40504030if 2
Figure 8. The three slots after each row; green slots changed on that row
RowX.SubjBlock that firesmaxsecondmaxthirdmax
130if 1 (30 > 0)3000
220if 2 (30 > 20 > 0)30200
350if 1 (50 > 30)503020
410none (10 is not above 20)503020
540if 2 (50 > 40 > 30)504030

After all five rows: max = 50, secondmax = 40, thirdmax = 30, exactly the top three marks, correctly ranked. The procedure returns 30.

Look at row 3: 50 beats max, so thirdmax takes the old secondmax (20), secondmax takes the old max (30), and only then max becomes 50. Copying from the bottom up is what keeps the old values from being overwritten.

2.4Step 2: the cutoff for each subject

Each cutoff is the mark you need to reach in that subject to be "top 3". One procedure, three calls with different parameters:

cutoffs.pseudo
cutoffMaths = TopThreeMarks(Mathematics)
cutoffPhys  = TopThreeMarks(Physics)
cutoffChem  = TopThreeMarks(Chemistry)

2.5Step 3: collect the students who clear each cutoff

Now scan the table once more. For every student, check their mark against each subject's cutoff, and append their sequence number to that subject's list if they clear it.

collect-lists.pseudo
mathsList = []
physList  = []
chemList  = []

while (Table 1 has more rows) {
    Read the first row X in Table 1
    if (X.Mathematics >= cutoffMaths) {
        mathsList = mathsList ++ [X.SeqNo]
    }
    if (X.Physics >= cutoffPhys) {
        physList = physList ++ [X.SeqNo]
    }
    if (X.Chemistry >= cutoffChem) {
        chemList = chemList ++ [X.SeqNo]
    }
    Move X to Table 2
}
Key idea

Using >= matters. Since cutoff scores can tie, more than 3 students may clear the "top 3" bar in a subject, and that is fine. With >, the student who scored exactly the cutoff would be left out.

Three separate ifs. The three tests are independent if blocks, not if ... else. One student can be appended to two or three lists in the same pass, which is exactly what the matching step needs.

2.6Step 4: students common to Maths and Physics

The same nested-foreach trick from Lecture 5.2: compare every entry in mathsList against every entry in physList.

maths-phys.pseudo
mathsPhysList = []
foreach x in mathsList {
    foreach y in physList {
        if (x == y) {
            mathsPhysList = mathsPhysList ++ [x]
        }
    }
}

2.7Step 5: bring in Chemistry too

Repeat the exact same matching step, but now between mathsPhysList (students already good at both Maths and Physics) and chemList. Whoever survives both rounds is a topper in all three subjects.

maths-phys-chem.pseudo
mathsPhysChemList = []
foreach x in mathsPhysList {
    foreach y in chemList {
        if (x == y) {
            mathsPhysChemList = mathsPhysChemList ++ [x]
        }
    }
}

2.8The whole pipeline on a small table

The lecture gives no data for this example, so here is a run on six illustrative students (not lecture data). All values below come from running the pseudocode.

SeqNoMathematicsPhysicsChemistry
0857092
1928875
2789588
3928190
4608870
5887695
  1. Cutoffs. Maths marks 85, 92, 78, 92, 60, 88 give cutoffMaths = 85. Physics gives cutoffPhys = 81, Chemistry gives cutoffChem = 90.
  2. Lists. mathsList = [0, 1, 3, 5], physList = [1, 2, 3, 4], chemList = [0, 3, 5].
  3. Round 1. Maths with Physics: mathsPhysList = [1, 3] (4 × 4 = 16 comparisons).
  4. Round 2. With Chemistry: mathsPhysChemList = [3] (2 × 3 = 6 comparisons). Student 3 is a topper in all three.
mathsList (cutoff 85)[0135]physList (cutoff 81)[1234]chemList (cutoff 90)[035]after Maths ∩ Physics[13]after adding Chemistry[3]
Figure 9. What survives each round in the illustrative run
Why does mathsList have four students? Two students tie at 92. TopThreeMarks uses strict comparisons, so the second 92 does not take a slot: the slots end as 92, 88, 85, and the cutoff is 85. With >=, the four students with 92, 92, 88 and 85 all clear it. This is the "more than 3 students" case the lecture mentions.

2.9Going deeper

  • The cutoff is the third-highest distinct mark (extra). Because every comparison in TopThreeMarks is strict, a repeated mark never takes a second slot. Marks 90, 90, 85, 80 give a cutoff of 80, and four students clear it.
  • An extreme tie (extra). If every student has the same mark, say 90, 90, 90, then secondmax and thirdmax stay 0, the cutoff is 0 and everyone is appended to that subject's list. A real solution would need a rule for this.
  • The table has to come back (extra). Each call of TopThreeMarks moves every row from Table 1 to Table 2, and Step 3 then scans Table 1 again. The lecture takes for granted that Table 1 is restored before each scan. That is the side-effect issue from Week 3: a procedure that moves the rows must put them back, or say so in its contract.
  • Name check. Lecture 5.2 writes X.Seqno, Lecture 5.4 writes X.SeqNo. They mean the same field; these notes keep each lecture's spelling.
  • Why lists here? The number of students that clear a cutoff is not known in advance (ties), so the answer must be a collection.

2.10Exam tips and common mistakes

Exam tips
  • To trace TopThreeMarks, keep a three-column table (max, secondmax, thirdmax) and update it row by row.
  • Remember the return value is thirdmax, the cutoff, not max.
  • Before matching, write each subject list out in full; then match two lists at a time.
Common mistakes
  • Updating max first and losing the old value before copying it down.
  • Using > instead of >= against the cutoff and dropping the student who scored exactly the cutoff.
  • Assuming each subject list has exactly 3 students.
  • Matching Maths with Chemistry and forgetting Physics: all three lists must take part.

Practice questions (graded-assignment style)

Q1The cutoff

Numerical Answer Type (NAT).

A subject's marks are read in the order 45, 70, 60, 90, 80. What does TopThreeMarks return?

Solution
Idea

Trace the three slots.

  • After 45: 45, 0, 0. After 70: 70, 45, 0. After 60: 70, 60, 45.
  • After 90: 90, 70, 60. After 80: 90, 80, 70.
  • Answer: 70
Q2How often max changes

Numerical Answer Type (NAT).

For the same marks 45, 70, 60, 90, 80, how many times does the first if block (the one for X.Subj > max) fire?

Solution
Idea

Count the new maxima.

  • 45 (above 0), 70 (above 45) and 90 (above 70).
  • Answer: 3
Q3Why >=

Multiple Choice Question (MCQ): choose the one correct option.

Why does Step 3 compare marks with the cutoff using >=?

1
It makes the loop faster
2
A student who scored exactly the cutoff is in the top 3 too, and ties can let more than 3 in
3
It removes duplicate SeqNos
4
It guarantees exactly 3 students per list
Solution
Idea

The cutoff is a mark a student actually scored.

  • The student whose mark is the cutoff must be included, and ties may let more than three in.
  • Answer: option 2.
Q4Ties

Numerical Answer Type (NAT).

In one subject the marks are 90, 90, 85, 80. How many students are appended to that subject's list in Step 3?

Solution
Idea

Find the cutoff first; ties do not take a second slot.

  • Slots end as 90, 85, 80, so the cutoff is 80.
  • All four marks are >= 80.
  • Answer: 4
Q5Matching

Multiple Choice Question (MCQ): choose the one correct option.

If mathsList = [0, 1, 3, 5], physList = [1, 2, 3, 4] and chemList = [0, 3, 5], what is mathsPhysChemList?

1
[3]
2
[1, 3]
3
[0, 3, 5]
4
[]
Solution
Idea

Match two lists at a time.

  • Maths with Physics: [1, 3]. With Chemistry: [3].
  • Answer: option 1.
Q6The pipeline

Multiple Select Question (MSQ): select all that apply.

Choose the correct statements about the Top Students solution.

1
TopThreeMarks is called once per subject
2
Only one of the three if blocks in TopThreeMarks fires for a row
3
A student can be appended to at most one subject list
4
Two rounds of nested foreach combine the three lists
Solution
Idea

Recall the five steps.

  • 1, 2 and 4 are true. The three subject tests are separate ifs, so one student can be in several lists (statement 3 is false).
  • Answer: options 1, 2 and 4.
Revision overview
The goalTop 3 in Maths, Physics
and Chemistry
Need a cutoff each
TopThreeMarksmax, secondmax, thirdmax
Shift down on a new mark
Returns thirdmax
Trace30, 20, 50, 10, 40
Ends 50, 40, 30
Cutoff 30
Top StudentsLecture 5.4
CutoffsOne call per subject
cutoffMaths, cutoffPhys
cutoffChem
ListsSecond scan
mark >= cutoff: append
Ties: more than 3
MatchingMaths with Physics
then with Chemistry
Survivors: all-round
Revision: from three cutoffs to the students who top all three subjects
Next · Lecture 5.4Matching More Than Two Lists
03
Lecture 5.4

Matching More Than Two Lists

Nested foreach on two lists at a time, chained to handle any number of lists.

The Maths, Physics and Chemistry example used two rounds of pairwise matching to combine three lists. The same idea scales to any number of lists.

3.1The pattern, generalised

The matching step always takes two lists and returns the items common to both. To combine more lists, you just chain the pairwise matching step: the output of one match becomes an input of the next.

3.2General approach: four lists

Say you need the items common to list1, list2, list3 and list4:

  1. Nested foreach on list1 and list2 gives list12, the items common to the first two.
  2. Nested foreach on list3 and list4 gives list34, the items common to the last two.
  3. Nested foreach on list12 and list34 gives the items common to all four.
round 1round 1list1[12345]list2[2357]list3[356]list4[1358]list12[235]list34[35]round 2[35]common to all four
Figure 10. Four illustrative lists: pair them up, then pair up the results
Key idea

This "pair them up, then pair up the results" strategy means you never need more than two nested loops at a time, no matter how many lists you are combining.

Written out in full (the names list12, list34, list1234 follow the lecture's steps; the slide gives the steps in words only):

four-lists.pseudo
// round 1
list12 = []
foreach x in list1 {
    foreach y in list2 {
        if (x == y) {
            list12 = list12 ++ [x]
        }
    }
}
list34 = []
foreach x in list3 {
    foreach y in list4 {
        if (x == y) {
            list34 = list34 ++ [x]
        }
    }
}
// round 2
list1234 = []
foreach x in list12 {
    foreach y in list34 {
        if (x == y) {
            list1234 = list1234 ++ [x]
        }
    }
}

3.3A run on four lists

With the illustrative lists of Figure 10:

StepLists matchedComparisonsResult
Round 1[1, 2, 3, 4, 5] and [2, 3, 5, 7]5 × 4 = 20list12 = [2, 3, 5]
Round 1[3, 5, 6] and [1, 3, 5, 8]3 × 4 = 12list34 = [3, 5]
Round 2[2, 3, 5] and [3, 5]3 × 2 = 6[3, 5]
Total38common to all four: 3 and 5

3.4Chaining one list at a time (extra)

The Top Students example combined its lists the other way: match the first two, then match that result with the third, and so on. For four lists: match list1 with list2, then that result with list3, then that result with list4. It also uses only two nested loops at a time, and it gives the same items:

StepLists matchedComparisonsResult
1list1 and list25 × 4 = 20[2, 3, 5]
2[2, 3, 5] and list33 × 3 = 9[3, 5]
3[3, 5] and list42 × 4 = 8[3, 5]
Total37common to all four: 3 and 5
Same answer, different work. Both orders find 3 and 5. The number of comparisons depends on the list sizes, and here chaining happens to need one fewer. Matching the shortest lists first keeps the intermediate lists small and is usually the cheaper order. This comparison is an extra remark; the lecture only presents the pairing strategy.

3.5Why lists matter here

  • Lists let you collect items that share some property (for example "top 3 in Physics") without knowing in advance how many there will be.
  • Nested foreach lets you find items that appear in two lists at once.
  • Grouping lists pairwise lets that same matching idea handle any number of lists.

3.6Going deeper

  • Any grouping gives the same set (extra). "Common to all" does not depend on which pairs you match first, so you are free to choose the grouping. Only the order of the items in the result and the amount of work can change.
  • Odd numbers of lists (extra). With five lists, pair 1 with 2 and 3 with 4, then match the two results, then match that with list 5. Every step is still one nested foreach.
  • An empty result ends the search early (extra). If any intermediate list is [], the final answer is [], whatever the other lists hold.
  • Cost (extra). One matching of m items against n items costs m × n comparisons, so the total is the sum over all the matching steps.

3.7Exam tips and common mistakes

Exam tips
  • Write each intermediate list out; most errors come from a wrong intermediate result.
  • For a count of comparisons, multiply the two lengths at each step and add the steps.
Common mistakes
  • Trying to write three or four foreach loops nested inside each other.
  • Matching list12 with list3 and forgetting list4.
  • Assuming the pairing order changes which items are common.

Practice questions (graded-assignment style)

Q1Comparisons in one match

Numerical Answer Type (NAT).

How many times is x == y checked when a list of 6 items is matched against a list of 3 items with nested foreach?

Solution
Idea

Outer length × inner length.

  • 6 × 3 = 18.
  • Answer: 18
Q2The pairing plan

Multiple Choice Question (MCQ): choose the one correct option.

To find the items common to A, B, C and D using the lecture's pairing strategy, what is matched in the last step?

1
A and D
2
AB and C
3
AB and CD
4
A, B, C and D in one loop
Solution
Idea

Pair up, then pair up the results.

  • Round 1 gives AB and CD; round 2 matches them.
  • Answer: option 3.
Q3Common to four

Numerical Answer Type (NAT).

For list1 = [1, 2, 3, 4, 5], list2 = [2, 3, 5, 7], list3 = [3, 5, 6], list4 = [1, 3, 5, 8], how many items are common to all four?

Solution
Idea

Compute list12 and list34 first.

  • list12 = [2, 3, 5], list34 = [3, 5], final [3, 5].
  • Answer: 2
Q4Scaling up

Multiple Select Question (MSQ): select all that apply.

Choose the correct statements.

1
The final set of common items does not depend on how the lists are grouped
2
Each matching step needs only two nested foreach loops
3
Pairing always needs fewer comparisons than chaining
4
Six lists can be combined with the same pairwise step
Solution
Idea

Think about what the matching step needs.

  • 1, 2 and 4 are true. Chaining needed 37 comparisons and pairing 38 on the lists of this chapter, so pairing is not always cheaper (statement 3 is false).
  • Answer: options 1, 2 and 4.
Revision overview
Pairwise matchTwo lists in
Common items out
Nested foreach
Four lists1 with 2: list12
3 with 4: list34
list12 with list34
Many ListsLecture 5.4
Chaining((1 with 2) with 3) with 4
Same items
Work may differ
Why listsUnknown sizes
Match two at once
Any number of lists
Revision: combining any number of lists two at a time
Next · Tutorial 5.1Core List Functions
04
Tutorial 5.1

Core List Functions

length, first, last, rest, init and member, each built from foreach, ++ and plain variables.

These six functions come up constantly once you start working with lists. Each one is built entirely out of things you already know: foreach, ++ and plain variables.

4.1The six functions

FunctionReturns
length(l)how many items
first(l)the first item
last(l)the final item
rest(l)everything except the first item
init(l)everything except the last item
member(l, e)True if e appears in l, else False
length(l)[2030405010]5first(l)[2030405010]20last(l)[2030405010]10rest(l)[2030405010][30,40,50,10]init(l)[2030405010][20,30,40,50]
Figure 11. The functions on l = [20, 30, 40, 50, 10]: the highlighted boxes are the items each answer uses
How the tutorial writes them. The tutorial writes these as length(l) { ... }, a short form of Procedure length(l) ... End length. Each takes a list as its parameter and returns a value with return(...).

4.2length(l): how many items?

Walk through the list once, adding 1 to a counter for every item you see.

length.pseudo
length(l) {
    count = 0
    foreach x in l {
        count = count + 1
    }
    return(count)
}
Result
length([20, 30, 40, 50, 10])  →  5
Passxcount after the pass
1201
2302
3403
4504
5105

This is the counting accumulator of earlier weeks, now running over a list instead of a pile of cards. length([]) is 0, because the loop body never runs.

4.3first(l): the first item

The trick here is neat: foreach starts from the very first item, so if you return immediately inside the loop, the loop never gets to a second item.

first.pseudo
first(l) {
    foreach x in l {
        return(x)
    }
}
Result
first([20, 30, 40, 50, 10])  →  20
Return ends the procedure

return does not just hand back a value; it stops the procedure at once, loop included. That is why only the first item is ever looked at.

4.4last(l): the final item

The opposite idea: keep overwriting a variable with the current item on every pass. By the time the loop ends, it is holding whatever came last.

last.pseudo
last(l) {
    foreach x in l {
        e = x
    }
    return(e)
}
Result
last([20, 30, 40, 50, 10])  →  10
Passxe after the pass
12020
23030
34040
45050
51010

4.5rest(l): everything except the first item

Use a flag. The flag starts False and flips to True the moment the first item is seen, but that first item is not added to the result. Every item after that gets appended.

rest.pseudo
rest(l) {
    found = False
    restList = []
    foreach x in l {
        if (found) {
            restList = restList ++ [x]
        } else {
            found = True
        }
    }
    return(restList)
}
Result
rest([20, 30, 40, 50, 10])  →  [30, 40, 50, 10]
Passxfound before the passWhat happensrestList after
120Falseelse: found = True (20 skipped)[]
230Trueappend 30[30]
340Trueappend 40[30, 40]
450Trueappend 50[30, 40, 50]
510Trueappend 10[30, 40, 50, 10]

4.6init(l): everything except the last item

Same flag idea, but shifted by one step: instead of appending the current item, you append the item from the previous pass (prev). That way the very last item never gets appended, because there is no next pass left to append it on.

init.pseudo
init(l) {
    found = False
    initList = []
    foreach x in l {
        if (found) {
            initList = initList ++ [prev]
        } else {
            found = True
        }
        prev = x
    }
    return(initList)
}
Result
init([20, 30, 40, 50, 10])  →  [20, 30, 40, 50]
x (current item)prev (item from the last pass)20—first pass3020403050401050appended to initList10never appended
Figure 12. prev lags one pass behind x, so 10 is never appended
Passxfound beforeWhat happensprev afterinitList after
120Falsefound = True20[]
230Trueappend prev = 2030[20]
340Trueappend prev = 3040[20, 30]
450Trueappend prev = 4050[20, 30, 40]
510Trueappend prev = 5010[20, 30, 40, 50]
Order inside the loop. prev = x is the last line of the loop body. The append uses the old prev first, then prev moves up to the current item. Swapping these two lines would append the current item and give back the whole list.

4.7member(l, e): does e appear in l?

Scan the list; the instant you find a match, return True and stop. If the loop finishes without ever matching, the item is not there: return False.

member.pseudo
member(l, e) {
    foreach x in l {
        if (e == x) {
            return(True)
        }
    }
    return(False)
}
Result
member([20, 30, 40, 50], 30)  →  True
member([20, 30, 40, 50], 10)  →  False
member([20, 30, 40, 50], 30)[20304050]✗✓return(True) here: the loop stopsnever looked at
Figure 13. member stops at the first match; the items after it are never looked at

member([20, 30, 40, 50], 30) compares 30 with 20, then with 30, and returns True after 2 comparisons. member([20, 30, 40, 50], 10) has to compare with all 4 items before it can say False.

Where return(False) sits. It is after the loop, not in an else inside it. Returning False as soon as one item does not match would wrongly answer False for member([20, 30], 30).

4.8Cheat sheet

FunctionReturnsOn [20, 30, 40, 50, 10]Built with
length(l)Number of items5counter + 1 per item
first(l)First item20return inside the loop
last(l)Last item10overwrite on every pass
rest(l)All but the first[30, 40, 50, 10]flag, skip the first
init(l)All but the last[20, 30, 40, 50]flag + prev
member(l, e)True / Falsemember(l, 30) → Truereturn True on a match

4.9Going deeper

  • Empty lists (extra). length([]) is 0, rest([]) and init([]) are [], member([], e) is False. But first([]) never reaches a return, and last([]) returns e without ever setting it, so both are undefined: call them only on non-empty lists.
  • One-item lists (extra). rest([7]) and init([7]) are both [].
  • Combining them (extra). first(rest(l)) is the second item, last(init(l)) the second-last, and rest(init(l)) drops both ends: on [20, 30, 40, 50, 10] these are 30, 50 and [30, 40, 50]. Also length(rest(l)) = length(l) − 1 for a non-empty list.
  • member simplifies matching (extra). The inner foreach of Lecture 5.2 is exactly a membership test, so the common-items code can be written with member:
may-chennai-with-member.pseudo
mayChennaiList = []
foreach x in mayList {
    if (member(chennaiList, x)) {
        mayChennaiList = mayChennaiList ++ [x]
    }
}

It does the same comparisons, but each one stops as soon as a match is found, and the code reads as "keep x if x is a member of chennaiList".

4.10Exam tips and common mistakes

Exam tips
  • Trace with a table: one row per pass, one column per variable (found, prev, the result list).
  • For member, count comparisons up to and including the match, or all of them if there is no match.
  • Evaluate nested calls from the inside out: first(rest(rest(l))) starts with the innermost rest.
Common mistakes
  • Confusing rest (drops the first) with init (drops the last).
  • Putting return(False) inside the loop of member.
  • Expecting rest or init to return a single item; they return lists.
  • Moving prev = x above the append in init.

Practice questions (graded-assignment style)

Q1Length with repeats

Numerical Answer Type (NAT).

What is length([4, 4, 4])?

Solution
Idea

Every item counts, repeated or not.

  • The counter goes 1, 2, 3.
  • Answer: 3
Q2rest of a one-item list

Multiple Choice Question (MCQ): choose the one correct option.

What is rest([7])?

1
7
2
[7]
3
[]
4
undefined
Solution
Idea

The only item is the first item.

  • On the only pass the flag flips and 7 is skipped.
  • Answer: option 3.
Q3init

Multiple Choice Question (MCQ): choose the one correct option.

What is init([5, 9, 2])?

1
[9, 2]
2
[5, 9]
3
[5]
4
2
Solution
Idea

Everything except the last item.

  • prev appends 5 on pass 2 and 9 on pass 3; 2 is never appended.
  • Answer: option 2.
Q4Nested calls

Numerical Answer Type (NAT).

Let l = [20, 30, 40, 50, 10]. What is first(rest(rest(l)))?

Solution
Idea

Work from the inside out.

  • rest gives [30, 40, 50, 10], then [40, 50, 10]; its first item is 40.
  • Answer: 40
Q5Comparisons in member

Numerical Answer Type (NAT).

How many times is e == x checked by member([20, 30, 40, 50], 10)?

Solution
Idea

No match means the whole list is scanned.

  • 10 is compared with 20, 30, 40 and 50, then the loop ends and False is returned.
  • Answer: 4
Q6Function facts

Multiple Select Question (MSQ): select all that apply.

For a list l with at least two items, choose the correct statements.

1
last(init(l)) is the second-last item
2
length(rest(l)) is length(l) − 1
3
first(l) == last(l) only when l has one item
4
member(l, first(l)) is True
Solution
Idea

Try them on [20, 30, 40, 50, 10] and on a list like [5, 3, 5].

  • 1, 2 and 4 are true. Statement 3 fails for [5, 3, 5]: first and last are both 5 but the length is 3.
  • Answer: options 1, 2 and 4.
Revision overview
lengthcount = count + 1
Per item
[] gives 0
firstreturn inside the loop
Stops at item 1
Undefined on []
laste = x each pass
Holds the final item
Undefined on []
List FunctionsTutorial 5.1
restFlag skips item 1
Appends the rest
[30, 40, 50, 10]
initFlag + prev
Appends the previous item
[20, 30, 40, 50]
memberreturn True on a match
return False after the loop
Early exit
Revision: six list functions, each built from foreach, ++ and variables
Next · All lecturesWeek 5 Summary Sheet
05
All lectures

Week 5 Summary Sheet

One page to revise all of Week 5: lists, ++ and foreach, the Top Students pipeline, matching many lists and the six list functions.

The big picture

Lecture 5.2 · Lists
  • A list is a sequence [x1, ..., xn] under one name; [] is empty.
  • Use one when you do not know in advance how many items you will collect.
Lecture 5.2 · ++ and foreach
  • l1 ++ l2 appends; l = l ++ [x] adds one item at the end.
  • foreach x in l visits every item, in order.
Lecture 5.2 · Common items
  • Nested foreach: outer picks a candidate, inner searches for it.
  • Lists of sizes m and n need m × n comparisons.
Lecture 5.4 · Top Students
  • TopThreeMarks returns the third-highest mark, the cutoff.
  • Collect with >=, then match Maths, Physics, Chemistry.
Lecture 5.4 · Many lists
  • Match two lists at a time; pair up the results.
  • Never more than two nested loops at once.
Tutorial 5.1 · List functions
  • length, first, last, rest, init, member.
  • Built from foreach, ++, a flag, prev and early return.

Patterns and how to use them

Build a list while scanning
Start empty, append matches
pseudocode
mayList = []
while (Table 1 has more rows) {
    Read the first row X in Table 1
    if (X.MonthOfBirth == "May") {
        mayList = mayList ++ [X.Seqno]
    }
    Move X to Table 2
}

Use whenYou need every row that satisfies a condition, and you do not know how many there will be.

  1. Set the list to [] before the loop.
  2. Inside the loop, test the condition on the current row.
  3. If it holds, append with list = list ++ [X.Seqno].
ExampleSix rows with months Nov, May, May, Jul, May, Feb (Seqnos 0 to 5): mayList grows [] → [1] → [1, 2] → [1, 2, 4].
Items common to two lists
Nested foreach
pseudocode
mayChennaiList = []
foreach x in mayList {
    foreach y in chennaiList {
        if (x == y) {
            mayChennaiList = mayChennaiList ++ [x]
        }
    }
}

Use whenYou want the items that satisfy two conditions, and each condition has produced its own list.

  1. Outer loop over the first list picks a candidate x.
  2. Inner loop over the second list looks for y == x.
  3. On a match, append x to the result list.
ExamplemayList = [1, 2, 4], chennaiList = [2, 3, 4]: 3 × 3 = 9 comparisons, result [2, 4].
Top three in one scan
The three cases
pseudocode
if (X.Subj > max) {
    thirdmax = secondmax
    secondmax = max
    max = X.Subj
}
if (max > X.Subj and X.Subj > secondmax) {
    thirdmax = secondmax
    secondmax = X.Subj
}
if (secondmax > X.Subj and X.Subj > thirdmax) {
    thirdmax = X.Subj
}

Use whenYou need the third-highest mark (the cutoff) of a subject in one pass.

  1. Start all three slots at 0.
  2. A new mark shifts every lower slot down one rank, copying from the bottom up.
  3. Return thirdmax; collect students with mark >= cutoff.
ExampleMarks 30, 20, 50, 10, 40 end as max 50, secondmax 40, thirdmax 30, so the cutoff is 30.
Matching many lists
Pair up, then pair the results
pseudocode
// match(a, b): the nested foreach
// that keeps the items common to a and b
list12 = match(list1, list2)
list34 = match(list3, list4)
answer = match(list12, list34)

Use whenYou need the items common to three or more lists.

  1. Match two lists at a time with nested foreach.
  2. Feed each result into the next match.
  3. Add up m × n for every match to get the comparisons.
Example[1, 2, 3, 4, 5], [2, 3, 5, 7], [3, 5, 6], [1, 3, 5, 8]: list12 = [2, 3, 5], list34 = [3, 5], answer [3, 5].
A flag to skip an item
rest(l)
pseudocode
rest(l) {
    found = False
    restList = []
    foreach x in l {
        if (found) {
            restList = restList ++ [x]
        } else {
            found = True
        }
    }
    return(restList)
}

Use whenYou must treat the first item differently from the others (rest, and with prev, init).

  1. Start the flag at False.
  2. On the first pass, only set it to True.
  3. From the second pass on, append (x for rest, prev for init).
ExampleFor l = [20, 30, 40, 50, 10]: rest(l) is [30, 40, 50, 10] and init(l) is [20, 30, 40, 50].
Return early
member(l, e)
pseudocode
member(l, e) {
    foreach x in l {
        if (e == x) {
            return(True)
        }
    }
    return(False)
}

Use whenThe answer is known as soon as one item is found (first, member).

  1. Put return inside the loop where the answer is decided.
  2. Put the "not found" answer after the loop.
  3. Count comparisons only up to the match.
Examplemember([20, 30, 40, 50], 30) is True after 2 comparisons; with 10 it is False after 4.

The list functions

FunctionReturnsOn [20, 30, 40, 50, 10]On []
length(l)number of items50
first(l)first item20undefined
last(l)last item10undefined
rest(l)all but the first[30, 40, 50, 10][]
init(l)all but the last[20, 30, 40, 50][]
member(l, e)True / Falsemember(l, 30) → TrueFalse

Which tool when?

SituationTool
Collect an unknown number of itemsA list, started as []
Join two listsl1 ++ l2 (order matters)
Add one item at the endl = l ++ [x]
Do something with every itemforeach x in l
Items in both of two listsNested foreach, or member inside one foreach
Items in three or more listsMatch two at a time, then match the results
Cutoff for "top 3" in a subjectTopThreeMarks(Subj), then >=
Is e in the list?member(l, e)

Common mistakes

l ++ x without brackets
  • ++ joins two lists. Write l = l ++ [x].
Treating ++ as commutative
  • [1, 13] ++ [2, 17, 1] and [2, 17, 1] ++ [1, 13] are different lists.
Resetting the list inside the loop
  • Put list = [] before the loop, or it is emptied on every row.
> instead of >= against the cutoff
  • The student who scored exactly the cutoff is in the top 3; ties can let in more than 3.
rest versus init
  • rest drops the first item, init drops the last. Both return lists.
return(False) inside member's loop
  • It belongs after the loop; inside, it would stop at the first non-matching item.
Back to top