SECTION 05 / 24

foreach visits values in list order

1 min read
foreach takes the next element value at each step. An empty list has no body executions.
foreach takes the next element value at each step. An empty list has no body executions.
REAL COURSE DATA · BUILD AND UNPACK LISTS

Visit each list occurrence

Follow one occurrence at a time. Choose another input to test empty lists, repeated IDs and different parameters.

Ready

CURRENT RECORD / VALUE

Ready to begin

No records have been processed. Start with Next step.

What we remember

Processed
0

Predict the next change, then step through the list. The original course records remain unchanged.

Count = 0
foreach x in MayIDs:
    Count = Count + 1
# Count = 4; x took 3, then 13, then 23, then 25.

x is the current element, not automatically a list index. In MayIDs, the first x is 3, even though it occupies the first position. The loop runs once per occurrence, including repeated values. A foreach loop does not need a manual move-to-next-card instruction in this list notation.

If the list is empty, the body runs zero times. Variables used after the loop must have meaningful initial values: Count = 0 works; a variable assigned only inside the loop may remain undefined. A return inside a function ends that function immediately, even if the foreach has more elements left.

The tutorial also permits foreach over rows or cards. The important idea is systematic traversal, not a rule that WHILE is only for cards and FOREACH is only for lists. Avoid changing the list being traversed unless the iteration contract explains how that change behaves.

Try it yourself

For [3,3,25], how many times does Count increase?

Show explained answer

Three times: once for each list position.

Try it yourself

If the input is [], what is Count after the displayed code?

Show explained answer

Zero. It was initialized before the loop, and no iteration changes it.

Try it yourself

Does foreach x in [3,13] make x equal to 1 and then 2?

Show explained answer

No. x becomes 3 and then 13. Positions and values are different.

YOUR STUDY PROGRESS

Finished this section? Save your progress.

Back to top ↑