Library contents

Python list slice insertion

Insert several stops at the same position by assigning to an empty slice.

A simple example

list slice insertion

  1. Start with A, C
  2. Do this Insert B between them
  3. Result A, B, C
Inserting at the middle shifts C one place to the right.

Syntax

Python syntax
stops[index:index] = extra_stops
Run these examples in Python

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

python3 lesson.py

Insert two pickup stops before the depot

A shuttle normally travels straight from the school to the depot. The dispatcher adds two afternoon pickups and needs them to appear in the supplied order before the final stop.

From the programstops = ["School", "Depot"]
ResultSchool, Hall, Pool, Depot
lesson.py
stops = ["School", "Depot"]
stops[1:1] = ["Hall", "Pool"]
print(", ".join(stops))
Output
School, Hall, Pool, Depot

The empty slice removes no stops and inserts the two pickup points before the depot.

Advertisements

Extend a reading list

A class has chosen one novel and adds two more titles. The desk adds the new entries after the existing ones. Read the resulting sequence in its recorded order.

GivenFern + Tide, Sky
Worked resultFern · Tide · Sky

Update an equipment checklist

A technician adds the final item after packing two pieces of equipment. The desk adds the new entries after the existing ones. Read the resulting sequence in its recorded order.

GivenLens, Stand + Cable
Worked resultLens · Stand · Cable

What to watch for

Assign an iterable of complete stop names. Assigning a single string would insert its characters.

Documentation for list slice insertion