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

30. Check the Library Shelves · Pair Two Lists

Use zip to match items by position and catch incomplete pairs.

Lesson files · lessons/iteration-patterns/pair-matching-lists

Before you start
- Use split() to read space-separated entries into a list.
- Use len() to count the items in a list.
- Use a for loop with two names to receive a number and a value.

By the end
- Use zip() to pair entries that share a position.
- Use a length check before pairing.
- Explain what zip() leaves out when one list is shorter.

Where you can use it
Pair equipment with peg labels from two ordered lists. Count both lists first so you can spot a missing label before assigning any pegs.

zip(left, right) takes the first item from each list, then the second item from each and so on. Write for name, code in zip(names, codes) to give each half of a pair a name. Pairing depends on position, so swapping two codes changes the result.

By default, zip() stops as soon as either list runs out. The example makes one pair. Craft has no code left to pair with it. Compare the lengths with !=, which gives True if the numbers differ. Put the pairing loop in the branch for equal lengths.

Predict
How many pairs does zip() produce in the example?
- Two pairs.
- One pair.

Worked example (example.py)

names = ["Chess", "Craft"]
codes = ["A3"]
for name, code in zip(names, codes):
    print(f"{name} - {code}")


Example result
Chess - A3

Read an equipment list on the first line and a peg label list on the second, using spaces between items on both lines. If the lengths differ, print Counts differ and skip the labels. Otherwise, print one line per pair. For net ball and P2 P1, print net goes on P2 and ball goes on P1 on separate lines.

Starter program (starter.py)

items = input().split()
pegs = input().split()
for item in items:
    print(item)


Starter input
net ball
P2 P1

Hint
Use != to compare the lengths. Put the zip() loop in the else block.

Case 1. Try the sample
Input
net ball
P2 P1
Expected output
net goes on P2
ball goes on P1

Case 2. Extra peg
Input
rope
P6 P7
Expected output
Counts differ

Case 3. Missing peg
Input
rope cone
P6
Expected output
Counts differ

Stretch
When there is a mismatch, also print the number of items and the number of pegs so the reader knows which list to check.

Reflect
How would an unchecked zip() hide a missing peg label?

Check your prediction
One pair. After the first pair the codes list has no items left, so zip() stops.
