Article
Going through a list with a loop
You have a list of 1,000 scores. You want the total, the highest score, or to know whether anyone scored 100. You will not write 1,000 lines. You write a loop that visits each element in turn. Visiting every element of a list, one after another, is called traversing the list.
FOR EACH: visit every element
FOR EACH item IN aList runs its body once for each element, from the first to the last. On each pass, the variable item holds that element's value.
scores ← [4, 9, 2]
FOR EACH item IN scores
{
DISPLAY(item)
}| Pass | item | Displayed |
|---|---|---|
| 1 | 4 | 4 |
| 2 | 9 | 9 |
| 3 | 2 | 2 |
The loop shows 4 9 2. Python has the same loop, and it reads almost like English:
item is a copy of the element. Changing item inside the loop (item ← item * 2) does not change the list.
Check your understanding
What is displayed when this code runs?
nums ← [3, 5, 8]
FOR EACH item IN nums
{
DISPLAY(item + 1)
}Using an index: all or part of a list
FOR EACH always visits the whole list. To visit only part of it, to know the position, or to change elements, use an index variable and a loop. You must increase the index yourself:
scores ← [4, 9, 2]
i ← 2
REPEAT UNTIL(i > LENGTH(scores))
{
DISPLAY(scores[i])
i ← i + 1
}Starting at index 2 skips the first element. This shows 9 2. (To visit the whole list, start with i ← 1.) In Python the index starts at 0, so "the second element onward" is range(1, len(scores)):
To change every element, use the index on the left of the arrow, as in scores[i] ← scores[i] * 2. Here i is the index, and the list really changes. Keep every index between 1 and LENGTH(aList): going one step too far is an error.
Typical algorithms
Almost every list algorithm is a loop with a small variable set up before it. Let nums ← [4, 9, 2, 7].
Sum and average. The accumulator starts at 0.
total ← 0
FOR EACH n IN nums
{
total ← total + n
}
DISPLAY(total)
DISPLAY(total / LENGTH(nums))The total is 22 and the average is 22 / 4 = 5.5. The output is 22 5.5.
Count the elements that match a test. Add 1 only when the test is true.
count ← 0
FOR EACH n IN nums
{
IF(n > 5)
{
count ← count + 1
}
}
DISPLAY(count)Only 9 and 7 are greater than 5, so it shows 2.
Largest (or smallest). Start with the first element, then replace it whenever you see a bigger one. (For the smallest, use <.)
largest ← nums[1]
FOR EACH n IN nums
{
IF(n > largest)
{
largest ← n
}
}
DISPLAY(largest)largest goes 4, 9 (then stays). It shows 9.
Filter into a new list. Start with an empty list and APPEND the elements that pass a test.
big ← []
FOR EACH n IN nums
{
IF(n > 5)
{
APPEND(big, n)
}
}
DISPLAY(big[1])
DISPLAY(big[2])
DISPLAY(LENGTH(big))big becomes [9, 7], in the original order. The output is 9 7 2.
Linear search. A linear search looks at the elements one by one from the start until it finds the target or reaches the end. Here it is as a procedure:
PROCEDURE contains(aList, target)
{
FOR EACH item IN aList
{
IF(item = target)
{
RETURN(true)
}
}
RETURN(false)
}RETURN ends the procedure at once, so the search stops at the first match. contains(nums, 7) is true. contains(nums, 5) is false. Notice that RETURN(false) is after the loop: it is only reached if no element matched. Run all of these in Python:
Check your understanding
What is displayed when this code runs?
nums ← [6, 2, 9, 4]
count ← 0
FOR EACH n IN nums
{
IF(n > 3)
{
count ← count + 1
}
}
DISPLAY(count)Common mistakes
- Starting the largest at 0. If every element is negative,
0is wrongly the "largest". Start from the first element. - Setting
total ← 0inside the loop. It resets on every pass. - Putting
RETURN(false)inside the loop. Then the search gives up after checking only the first element. - Thinking
itemis an index. InFOR EACH item IN aList,itemis the value, not its position. - Going one past the end. With an index loop,
imust stay at mostLENGTH(aList). - Mixing up AP and Python indexes in an index loop. AP starts at 1, Python at 0.
On the exam
Expect a list and a loop, and a question such as "What is displayed?" or "Which code finds the largest value?" Trace with a table: one row per element, with a column for the loop variable and one for every other variable. Check where each variable is set up and whether it is inside or outside the loop.
Key words
Traverse: visit the elements of a list one by one.
FOR EACH: AP loop that runs its body once for every element of a list.
Linear search: looking through a list element by element until the target is found or the list ends.
Filter: building a new list from the elements that pass a test.