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

29. Check the Library Shelves · Number What You Visit

Use enumerate to get a position and a value on each trip through a loop.

Lesson files · lessons/iteration-patterns/number-items-with-enumerate

Before you start
- Use a for loop to visit items in a list.
- Use split() to make a list from a line of text.
- Use len() to see whether a list is empty.

By the end
- Use enumerate() to get a label number and an item in the same loop.
- Explain how two equal codes can get different numbers.
- Test the label output with a line containing only spaces.

Where you can use it
Print a numbered list of projects for a class show. Start the labels at 1 and number every entry even if two projects have the same name.

A plain for loop over a list gives you one item at a time. enumerate() gives you two things each time, a counter and the item. In for number, code in enumerate(books, start=1), Python assigns those two values to number and code.

The counter starts at 0 by default. Use start=1 to number labels from 1 while the position of each item in the list stays the same. Try two items with the same code to see them get separate labels.

Predict
Which number would Studio get if you left out start=1?
- 1
- 2

Worked example (example.py)

rooms = ["Lab", "Studio"]
for number, room in enumerate(rooms, start=1):
    print(f"Stop {number} - {room}")


Example result
Stop 1 - Lab
Stop 2 - Studio

Read a line of book codes separated by spaces. Print one label per code, starting at 1 and keeping the input order. For AT BR, print Shelf 1 - AT and Shelf 2 - BR on separate lines. For a line containing only spaces, print No books.

Starter program (starter.py)

books = input().split()
for code in books:
    print(code)


Starter input
AT BR

Hint
Use split() to make a list of codes. Check len(books) before numbering the codes with enumerate().

Case 1. Try the sample
Input
AT BR
Expected output
Shelf 1 - AT
Shelf 2 - BR

Case 2. Repeated codes
Input
AT AT
Expected output
Shelf 1 - AT
Shelf 2 - AT

Case 3. Empty shelf
Input
   
Expected output
No books

Stretch
Read the starting label number on a second line so one report can continue the numbering from another.

Reflect
What information does enumerate() give you when two items have the same value?

Check your prediction
1 enumerate() starts at 0 by default. Lab would get 0 and Studio would get 1.
