Library contents

Python List item assignment

Update a stop at an existing index while keeping the other stops in place.

A simple example

List item assignment

  1. Start with A, B
  2. Do this Replace the second item with C
  3. Result A, C
Replacing one element keeps the number of elements at two.

Syntax

Python syntax
stops[index] = new_stop
Run these examples in Python

Save one example at a time as lesson.py. Use Python 3.9 or later.

python3 lesson.py

Correct the second stop on a shuttle route

A dispatcher spots an outdated address at the second stop on today's shuttle route. The position on the schedule is correct, so only the destination at that position should change.

From the programstops = ["School", "Park"]
ResultHarbor
lesson.py
stops = ["School", "Park"]
stops[1] = "Harbor"
print(stops[1])
Output
Harbor

Replacing index one changes the destination of the second stop.

Advertisements

Correct a lab register

A student signed the lab sheet with a nickname. The second entry must be corrected in place. Which value occupies that position after the change?

GivenAda · Kit → replace Kit with Kiran
Worked resultKiran

Change the next stop

The shuttle cannot use the quay this morning. The second entry must be corrected in place. Which value occupies that position after the change?

GivenSchool · Quay → replace Quay with Pier
Worked resultPier

What to watch for

Assignment beyond the end raises IndexError. Append a new entry when the route grows.

Documentation for List item assignment