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.
Chapters
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.
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:
[1, 13, 2]
["Vedanayagam", "cane", "Monday", "school"]
[] // an empty list — perfectly valid, has zero itemsA 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.
[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 = [1, 13] and l2 = [2, 17, 1], then l1 ++ l2 gives [1, 13, 2, 17, 1].- Order matters (extra).
l2 ++ l1gives[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:
l = l ++ [x] // extends l with item x"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.
mayList.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:
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):
| Row read | MonthOfBirth | Condition | mayList after the row |
|---|---|---|---|
| 0 | Nov | False | [] |
| 1 | May | True | [1] |
| 2 | May | True | [1, 2] |
| 3 | Jul | False | [1, 2] |
| 4 | May | True | [1, 2, 4] |
| 5 | Feb | False | [1, 2, 4] |
On the same six rows, the Chennai loop gives chennaiList = [2, 3, 4].
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 x in l {
Do something with x
}while over a table | foreach over a list | |
|---|---|---|
| Walks through | rows of a table | items of a list |
| Current element | Read the first row X | the loop variable x |
| Moving on | Move X to Table 2 (by hand) | automatic |
| Stops | when Table 1 has no more rows | after the last item |
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.
mayChennaiList = []
foreach x in mayList {
foreach y in chennaiList {
if (x == y) {
mayChennaiList = mayChennaiList ++ [x]
}
}
}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.
- Outer x = 1: compare with 2, 3, 4. No match.
- Outer x = 2: compare with 2 (match, append 2), 3, 4.
- Outer x = 4: compare with 2, 3, 4 (match, append 4).
- Result:
mayChennaiList = [2, 4]after 3 × 3 = 9 comparisons.
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 inl.
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).
mayChennaiListlists matches in the order they appear inmayList. - 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
ifjoinsX.MonthOfBirth == "May"andX.TownCity == "Chennai"withandalso works. Matching lists is the general tool when the lists come from different scans or different procedures.
1.10Exam tips and common mistakes
- 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.
- Writing
l = l ++ x: x must be wrapped as[x]. - Thinking
l1 ++ l2equalsl2 ++ 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)
Numerical Answer Type (NAT).
If l1 = [1, 13] and l2 = [2, 17, 1], how many items does l1 ++ l2 have?
Append keeps every item of both lists.
[1, 13, 2, 17, 1]has 2 + 3 items.- Answer: 5
Multiple Choice Question (MCQ): choose the one correct option.
Which statement adds the item 7 to the end of list l?
l = l ++ 7l = l ++ [7]l = [7] ++ ll = [l] ++ [7]++ joins two lists, so 7 must become a list.
l ++ 7joins a list with a number, which is not allowed.[7] ++ lputs 7 at the front.- Answer: option 2.
Multiple Choice Question (MCQ): choose the one correct option.
With l1 = [1, 13] and l2 = [2, 17, 1], what is l2 ++ l1?
[1, 13, 2, 17, 1][1, 2, 13, 17][2, 17, 1, 1, 13][2, 17, 1, 13]The left list comes first.
- The items of l2, then the items of l1:
[2, 17, 1, 1, 13]. - Answer: option 3.
Numerical Answer Type (NAT).
What is the length of l after this code runs?
l = []
foreach x in [3, 8, 5, 8] {
if (x > 4) {
l = l ++ [x]
}
}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
Numerical Answer Type (NAT).
mayList has 4 items and chennaiList has 5. How many times is x == y checked by the nested foreach?
The inner loop runs fully for every outer item.
4 × 5 = 20.- Answer: 20
Multiple Select Question (MSQ): select all that apply.
Choose the correct statements.
[] is a valid list with zero itemsl1 ++ l2 is always equal to l2 ++ l1foreach visits every item of the list once, in orderRecall 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.
Unknown number of items
One name, whole sequence
Strings allowed
[] is the empty list
= [1, 13, 2, 17, 1]
Order matters
Start from []
Append matching rows
x takes each value
No Move step needed
Keep x when x == y
m × n comparisons
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.
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.
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 TopThreeMarksOnly 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.
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
| Row | X.Subj | Block that fires | max | secondmax | thirdmax |
|---|---|---|---|---|---|
| 1 | 30 | if 1 (30 > 0) | 30 | 0 | 0 |
| 2 | 20 | if 2 (30 > 20 > 0) | 30 | 20 | 0 |
| 3 | 50 | if 1 (50 > 30) | 50 | 30 | 20 |
| 4 | 10 | none (10 is not above 20) | 50 | 30 | 20 |
| 5 | 40 | if 2 (50 > 40 > 30) | 50 | 40 | 30 |
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:
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.
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
}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.
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.
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.
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.
| SeqNo | Mathematics | Physics | Chemistry |
|---|---|---|---|
| 0 | 85 | 70 | 92 |
| 1 | 92 | 88 | 75 |
| 2 | 78 | 95 | 88 |
| 3 | 92 | 81 | 90 |
| 4 | 60 | 88 | 70 |
| 5 | 88 | 76 | 95 |
- Cutoffs. Maths marks 85, 92, 78, 92, 60, 88 give
cutoffMaths = 85. Physics givescutoffPhys = 81, Chemistry givescutoffChem = 90. - Lists.
mathsList = [0, 1, 3, 5],physList = [1, 2, 3, 4],chemList = [0, 3, 5]. - Round 1. Maths with Physics:
mathsPhysList = [1, 3](4 × 4 = 16 comparisons). - Round 2. With Chemistry:
mathsPhysChemList = [3](2 × 3 = 6 comparisons). Student 3 is a topper in all three.
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
TopThreeMarksis 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
secondmaxandthirdmaxstay 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
TopThreeMarksmoves 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 writesX.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
- 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, notmax. - Before matching, write each subject list out in full; then match two lists at a time.
- Updating
maxfirst 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)
Numerical Answer Type (NAT).
A subject's marks are read in the order 45, 70, 60, 90, 80. What does TopThreeMarks return?
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
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?
Count the new maxima.
- 45 (above 0), 70 (above 45) and 90 (above 70).
- Answer: 3
Multiple Choice Question (MCQ): choose the one correct option.
Why does Step 3 compare marks with the cutoff using >=?
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.
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?
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
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?
[3][1, 3][0, 3, 5][]Match two lists at a time.
- Maths with Physics:
[1, 3]. With Chemistry:[3]. - Answer: option 1.
Multiple Select Question (MSQ): select all that apply.
Choose the correct statements about the Top Students solution.
TopThreeMarks is called once per subjectif blocks in TopThreeMarks fires for a rowRecall 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.
and Chemistry
Need a cutoff each
Shift down on a new mark
Returns thirdmax
Ends 50, 40, 30
Cutoff 30
cutoffMaths, cutoffPhys
cutoffChem
mark >= cutoff: append
Ties: more than 3
then with Chemistry
Survivors: all-round
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:
- Nested foreach on
list1andlist2giveslist12, the items common to the first two. - Nested foreach on
list3andlist4giveslist34, the items common to the last two. - Nested foreach on
list12andlist34gives the items common to all four.
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):
// 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:
| Step | Lists matched | Comparisons | Result |
|---|---|---|---|
| Round 1 | [1, 2, 3, 4, 5] and [2, 3, 5, 7] | 5 × 4 = 20 | list12 = [2, 3, 5] |
| Round 1 | [3, 5, 6] and [1, 3, 5, 8] | 3 × 4 = 12 | list34 = [3, 5] |
| Round 2 | [2, 3, 5] and [3, 5] | 3 × 2 = 6 | [3, 5] |
| Total | 38 | common 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:
| Step | Lists matched | Comparisons | Result |
|---|---|---|---|
| 1 | list1 and list2 | 5 × 4 = 20 | [2, 3, 5] |
| 2 | [2, 3, 5] and list3 | 3 × 3 = 9 | [3, 5] |
| 3 | [3, 5] and list4 | 2 × 4 = 8 | [3, 5] |
| Total | 37 | common to all four: 3 and 5 |
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
foreachlets 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 × ncomparisons, so the total is the sum over all the matching steps.
3.7Exam tips and common mistakes
- 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.
- 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)
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?
Outer length × inner length.
6 × 3 = 18.- Answer: 18
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?
Pair up, then pair up the results.
- Round 1 gives AB and CD; round 2 matches them.
- Answer: option 3.
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?
Compute list12 and list34 first.
list12 = [2, 3, 5],list34 = [3, 5], final[3, 5].- Answer: 2
Multiple Select Question (MSQ): select all that apply.
Choose the correct statements.
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.
Common items out
Nested foreach
3 with 4: list34
list12 with list34
Same items
Work may differ
Match two at once
Any number of lists
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
| Function | Returns |
|---|---|
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) { ... }, 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(l) {
count = 0
foreach x in l {
count = count + 1
}
return(count)
}length([20, 30, 40, 50, 10]) → 5| Pass | x | count after the pass |
|---|---|---|
| 1 | 20 | 1 |
| 2 | 30 | 2 |
| 3 | 40 | 3 |
| 4 | 50 | 4 |
| 5 | 10 | 5 |
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(l) {
foreach x in l {
return(x)
}
}first([20, 30, 40, 50, 10]) → 20return 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(l) {
foreach x in l {
e = x
}
return(e)
}last([20, 30, 40, 50, 10]) → 10| Pass | x | e after the pass |
|---|---|---|
| 1 | 20 | 20 |
| 2 | 30 | 30 |
| 3 | 40 | 40 |
| 4 | 50 | 50 |
| 5 | 10 | 10 |
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(l) {
found = False
restList = []
foreach x in l {
if (found) {
restList = restList ++ [x]
} else {
found = True
}
}
return(restList)
}rest([20, 30, 40, 50, 10]) → [30, 40, 50, 10]| Pass | x | found before the pass | What happens | restList after |
|---|---|---|---|---|
| 1 | 20 | False | else: found = True (20 skipped) | [] |
| 2 | 30 | True | append 30 | [30] |
| 3 | 40 | True | append 40 | [30, 40] |
| 4 | 50 | True | append 50 | [30, 40, 50] |
| 5 | 10 | True | append 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(l) {
found = False
initList = []
foreach x in l {
if (found) {
initList = initList ++ [prev]
} else {
found = True
}
prev = x
}
return(initList)
}init([20, 30, 40, 50, 10]) → [20, 30, 40, 50]| Pass | x | found before | What happens | prev after | initList after |
|---|---|---|---|---|---|
| 1 | 20 | False | found = True | 20 | [] |
| 2 | 30 | True | append prev = 20 | 30 | [20] |
| 3 | 40 | True | append prev = 30 | 40 | [20, 30] |
| 4 | 50 | True | append prev = 40 | 50 | [20, 30, 40] |
| 5 | 10 | True | append prev = 50 | 10 | [20, 30, 40, 50] |
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(l, e) {
foreach x in l {
if (e == x) {
return(True)
}
}
return(False)
}member([20, 30, 40, 50], 30) → True
member([20, 30, 40, 50], 10) → Falsemember([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.
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
| Function | Returns | On [20, 30, 40, 50, 10] | Built with |
|---|---|---|---|
length(l) | Number of items | 5 | counter + 1 per item |
first(l) | First item | 20 | return inside the loop |
last(l) | Last item | 10 | overwrite 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 / False | member(l, 30) → True | return True on a match |
4.9Going deeper
- Empty lists (extra).
length([])is 0,rest([])andinit([])are[],member([], e)is False. Butfirst([])never reaches areturn, andlast([])returnsewithout ever setting it, so both are undefined: call them only on non-empty lists. - One-item lists (extra).
rest([7])andinit([7])are both[]. - Combining them (extra).
first(rest(l))is the second item,last(init(l))the second-last, andrest(init(l))drops both ends: on[20, 30, 40, 50, 10]these are 30, 50 and[30, 40, 50]. Alsolength(rest(l)) = length(l) − 1for 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:
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
- 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 innermostrest.
- Confusing
rest(drops the first) withinit(drops the last). - Putting
return(False)inside the loop ofmember. - Expecting
restorinitto return a single item; they return lists. - Moving
prev = xabove the append ininit.
Practice questions (graded-assignment style)
Numerical Answer Type (NAT).
What is length([4, 4, 4])?
Every item counts, repeated or not.
- The counter goes 1, 2, 3.
- Answer: 3
Multiple Choice Question (MCQ): choose the one correct option.
What is rest([7])?
7[7][]The only item is the first item.
- On the only pass the flag flips and 7 is skipped.
- Answer: option 3.
Multiple Choice Question (MCQ): choose the one correct option.
What is init([5, 9, 2])?
[9, 2][5, 9][5]2Everything except the last item.
- prev appends 5 on pass 2 and 9 on pass 3; 2 is never appended.
- Answer: option 2.
Numerical Answer Type (NAT).
Let l = [20, 30, 40, 50, 10]. What is first(rest(rest(l)))?
Work from the inside out.
restgives[30, 40, 50, 10], then[40, 50, 10]; its first item is 40.- Answer: 40
Numerical Answer Type (NAT).
How many times is e == x checked by member([20, 30, 40, 50], 10)?
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
Multiple Select Question (MSQ): select all that apply.
For a list l with at least two items, choose the correct statements.
last(init(l)) is the second-last itemlength(rest(l)) is length(l) − 1first(l) == last(l) only when l has one itemmember(l, first(l)) is TrueTry 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.
Per item
[] gives 0
Stops at item 1
Undefined on []
Holds the final item
Undefined on []
Appends the rest
[30, 40, 50, 10]
Appends the previous item
[20, 30, 40, 50]
return False after the loop
Early exit
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
- 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.
l1 ++ l2appends;l = l ++ [x]adds one item at the end.foreach x in lvisits every item, in order.
- Nested foreach: outer picks a candidate, inner searches for it.
- Lists of sizes m and n need
m × ncomparisons.
TopThreeMarksreturns the third-highest mark, the cutoff.- Collect with
>=, then match Maths, Physics, Chemistry.
- Match two lists at a time; pair up the results.
- Never more than two nested loops at once.
- length, first, last, rest, init, member.
- Built from foreach, ++, a flag, prev and early return.
Patterns and how to use them
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.
- Set the list to
[]before the loop. - Inside the loop, test the condition on the current row.
- If it holds, append with
list = list ++ [X.Seqno].
mayList grows [] → [1] → [1, 2] → [1, 2, 4].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.
- Outer loop over the first list picks a candidate x.
- Inner loop over the second list looks for y == x.
- On a match, append x to the result list.
mayList = [1, 2, 4], chennaiList = [2, 3, 4]: 3 × 3 = 9 comparisons, result [2, 4].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.
- Start all three slots at 0.
- A new mark shifts every lower slot down one rank, copying from the bottom up.
- Return
thirdmax; collect students withmark >= cutoff.
// 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.
- Match two lists at a time with nested foreach.
- Feed each result into the next match.
- Add up
m × nfor every match to get the comparisons.
[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].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).
- Start the flag at False.
- On the first pass, only set it to True.
- From the second pass on, append (x for rest, prev for init).
l = [20, 30, 40, 50, 10]: rest(l) is [30, 40, 50, 10] and init(l) is [20, 30, 40, 50].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).
- Put
returninside the loop where the answer is decided. - Put the "not found" answer after the loop.
- Count comparisons only up to the match.
member([20, 30, 40, 50], 30) is True after 2 comparisons; with 10 it is False after 4.The list functions
| Function | Returns | On [20, 30, 40, 50, 10] | On [] |
|---|---|---|---|
length(l) | number of items | 5 | 0 |
first(l) | first item | 20 | undefined |
last(l) | last item | 10 | undefined |
rest(l) | all but the first | [30, 40, 50, 10] | [] |
init(l) | all but the last | [20, 30, 40, 50] | [] |
member(l, e) | True / False | member(l, 30) → True | False |
Which tool when?
| Situation | Tool |
|---|---|
| Collect an unknown number of items | A list, started as [] |
| Join two lists | l1 ++ l2 (order matters) |
| Add one item at the end | l = l ++ [x] |
| Do something with every item | foreach x in l |
| Items in both of two lists | Nested foreach, or member inside one foreach |
| Items in three or more lists | Match two at a time, then match the results |
| Cutoff for "top 3" in a subject | TopThreeMarks(Subj), then >= |
| Is e in the list? | member(l, e) |
Common mistakes
++joins two lists. Writel = l ++ [x].
[1, 13] ++ [2, 17, 1]and[2, 17, 1] ++ [1, 13]are different lists.
- Put
list = []before the loop, or it is emptied on every row.
- The student who scored exactly the cutoff is in the top 3; ties can let in more than 3.
restdrops the first item,initdrops the last. Both return lists.
- It belongs after the loop; inside, it would stop at the first non-matching item.