Python List slicing
Select a batch from an inclusive start up to an exclusive stop.
A simple example
List slicing
- Start with A, B, C
- Do this Select the first two items
- Result A, B
Syntax
orders[start:stop]
Run these examples in Python
Save one example at a time as lesson.py. Use Python 3.9 or later.
python3 lesson.pySelect two orders for the packing bench
A packing bench takes a small batch from the middle of the day's queue. The supervisor wants orders B and C on this bench while the other orders stay visible in the full queue.
orders = ["A", "B", "C", "D"]
print(", ".join(orders[1:3]))
B, C
The slice contains positions one and two.
Prepare the next workshop roster
A teacher reads a workshop roster in arrival order. The coordinator prints the first two entries on a separate slip. Which entries appear, in order?
Work from the delivery round
A courier has three labelled stops in route order. The coordinator prints the first two entries on a separate slip. Which entries appear, in order?
What to watch for
A list slice creates a shallow copy. Changes to the slice's membership do not edit the original order queue.