Lesson explanation
After this lesson, you will be able to:
start:stop while remembering that stop is exclusive.[:] or .copy() before changing its elements.A slice selects several items without manually indexing each one. With items[start:stop], start is included and stop is not. For example, items[1:4] returns items at indexes 1, 2, and 3.
A slice may omit either bound: items[:3] takes the first three items, and items[2:] takes everything from index 2 onward. Negative bounds count from the end, as you practiced in the previous lesson. items[::2] takes every second item using a positive step. Unlike indexing, a slice whose end goes beyond the list length simply stops at the available items.
Copying matters when data is mutable. candidate = baseline does not create a new list; both names refer to the same object. By contrast, candidate = baseline[:] or candidate = baseline.copy() creates a new outer list. Updating a top-level element in the copy will not change the original.
These are shallow copies: if the list contains mutable nested objects, those nested objects are still shared. We will handle deeper structures later.
The end position is not included.
stages = ["fetch", "build", "test", "package", "deploy"]
print(stages[1:4])Output:
['build', 'test', 'package']The element at index 4 is left out.
Leaving out the start or stop makes it easy to select items from either end.
regions = ["eu", "us", "apac", "sa", "ca"]
print(regions[:2])
print(regions[-2:])Output:
['eu', 'us']
['sa', 'ca']The negative start selects the final two items.
A third slice value chooses how far to move between selected items.
readings = [8, 9, 10, 11, 12, 13]
print(readings[::2])Output:
[8, 10, 12]The selection starts at the first element and advances by two.
A slice copy gives a new list that can be updated independently.
baseline = ["queued", "running", "done"]
preview = baseline[:]
preview[1] = "paused"
print(baseline)
print(preview)Output:
['queued', 'running', 'done']
['queued', 'paused', 'done']baseline does not change. Calling baseline.copy() is another way to make this kind of copy.
| Need | Syntax |
|---|---|
Take from start through stop - 1 | items[:stop] |
Take from start to end | items[start:] |
| Take a middle window | items[start:stop] |
| Take every second item | items[::2] |
| Copy the outer list | items[:] or items.copy() |
| Create another name for same list | alias = items |
IndexError: it safely returns the available portion.candidate = baseline as a copy: both names then point to the same list.[:] and .copy() only copy the outer list.