Library contents

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

  1. Start with A, B, A
  2. Do this Find the first A
  3. Result Index 0
Python counts from zero. The search ends at the first element.

Syntax

Python 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.py

Look 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.

From the programservices = ["standard", "express", "express"]
Result9
lesson.py
services = ["standard", "express", "express"]
rates = [5, 9, 12]
position = services.index("express")
print(rates[position])
Output
9

The first express entry has index one and selects the rate of nine.

Advertisements

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.

GivenLake · Hill · Mill · Hill
Worked result1

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.

GivenPen · Ruler · Pen
Worked result0

What to watch for

A missing item raises ValueError. A dictionary is often simpler for repeated lookups with unique keys.

Documentation for list.index