──────────────────────────────────────

17. Repair Desk Intake · Preview the Next Slip

Preview one item from an iterator and process the rest in the same pass.

Lesson files · lessons/iterators-and-toolkit/preview-an-iterator

Before you start
- Use split() to read space-separated codes into a list.
- Use a for loop, enumerate() and zip() to visit items in order.

By the end
- Use iter() and next() to preview one value and pass the rest to a loop.
- Handle an empty iterator with the default argument to next().
- Predict what changes when you loop over the original list.

Where you can use it
A repair volunteer can preview the first scanned slip before processing the remaining slips in order.

A list is an iterable. Calling iter(codes) gives you an iterator over its values. The iterator keeps its position as next() consumes items. You have already used the iterators returned by enumerate() and zip().

In the example, next(scans) takes the first code. The for loop continues from that position. At the end, next(scans, "Finished") returns the default. A call without a default raises StopIteration at the end. Calling iter(codes) again makes a fresh iterator from the start of the list.

Predict
What does next(scans, "Finished") return after the loop?
- Finished
- R17

Worked example (example.py)

codes = ["R17", "R20"]
scans = iter(codes)

print(next(scans))
for code in scans:
    print(code)
print(next(scans, "Finished"))
print(next(iter(codes)))


Example result
R17
R20
Finished
R17

Enter space-separated slip codes on one line. Print “Preview: ” followed by the first code, then print each remaining code on its own line with “Next: ”. Print “No slips.” if the line is empty or absent. Keep repeated codes in order.

Starter program (starter.py)

import sys

codes = sys.stdin.readline().split()
scans = iter(codes)
for code in scans:
    print(f"Next: {code}")


Starter input
R02 R08 R11

Hint
Use next(scans, None) to read the preview. If it returns a code, loop over that same scans iterator.

Case 1. Try the sample
Input
R02 R08 R11
Expected output
Preview: R02
Next: R08
Next: R11

Case 2. Two slips with the same code
Input
R11 R11
Expected output
Preview: R11
Next: R11

Case 3. Empty input
Input
(No input.)
Expected output
No slips.

Stretch
After the report, use next(iter(codes), None) to see whether a fresh scan can preview the first slip again.

Reflect
What changes if the second loop visits codes instead of scans?

Check your prediction
Finished The loop used up scans, so next() returns the default. The last line makes a fresh iterator over the list.
