Python list slice insertion
Insert several stops at the same position by assigning to an empty slice.
A simple example
list slice insertion
- Start with A, C
- Do this Insert B between them
- Result A, B, C
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.pyInsert 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.
stops = ["School", "Depot"]
stops[1:1] = ["Hall", "Pool"]
print(", ".join(stops))
School, Hall, Pool, Depot
The empty slice removes no stops and inserts the two pickup points before the depot.
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.
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.
What to watch for
Assign an iterable of complete stop names. Assigning a single string would insert its characters.