Python list.index and reverse search
Find the first market stop with index and locate the last by searching a reversed copy.
A simple example
list.index and reverse search
- Start with A, B, A
- Do this Locate the first and last A
- Result First and third positions
Syntax
stops.index(stop)
Run these examples in Python
Save one example at a time as lesson.py. Use Python 3.9 or later.
python3 lesson.pyFind both visits to the market
A circular bus route visits the market on both the outward and return journeys. A timetable editor needs the first and last positions of the market to label the two visits correctly.
stops = ["Depot", "Market", "Park", "Market"]
first = stops.index("Market")
last = len(stops) - 1 - stops[::-1].index("Market")
print(f"{first} and {last}")
1 and 3
The reversed list starts at the original end, so subtracting its index from the last position gives three.
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
index raises ValueError if the stop is absent. Reversing by slicing creates a new list.