Python list.index
Find the position of the first matching service and use that position in a parallel list of rates.
A simple example
list.index
- Start with A, B, A
- Do this Find the first A
- Result Index 0
Syntax
services.index("express")
Run these examples in Python
Save one example at a time as lesson.py. Use Python 3.9 or later.
python3 lesson.pyLook up a rate by its position
A pricing screen selects a rate using its position in a collection. Check how the collection numbers its entries so the displayed rate belongs to the requested item.
services = ["standard", "express", "express"]
rates = [5, 9, 12]
position = services.index("express")
print(rates[position])
9
The first express entry has index one and selects the rate of nine.
Locate a transfer stop
A bus calls at Hill twice on its circular route. Find the first occurrence and count the entries before it. The duplicate later in the list does not change that count.
Find a returned item
A desk checks the earliest entry marked Pen. Find the first occurrence and count the entries before it. The duplicate later in the list does not change that count.
What to watch for
A missing item raises ValueError. A dictionary is often simpler for repeated lookups with unique keys.