Python List Slices and Slice Assignment
Core idea
items[start:stop] creates a new list of the selected items; stop is excluded, as with strings. Omit start or stop to reach the beginning or end. In contrast, items[start:stop] = values modifies the existing list. For a normal slice with step 1, the replacement can contain a different number of items.
scores = [4, 8, 12, 16]part = scores[1:3]print(part)print(scores)The slice contains indices 1 and 2. Reading a slice does not change the original.
Replace two items with one
slots = [10, 20, 30, 40]slots[1:3] = [99]print(slots)Two old items are replaced by one, shortening the list.
Empty slice and insertion
items = [1, 4]print(items[1:1])items[1:1] = [2, 3]print(items)The selected segment is empty, so assigning two items inserts them without replacing anything.
Common mistake
items[1] = [8, 9] stores a single nested list; items[1:2] = [8, 9] replaces one slot with two items. Slices with a step other than 1 require equal replacement lengths.
Practice
Extract the middle two items of [1, 2, 3, 4]. Then replace that segment with [20, 30, 40] and compare lengths.
Check Your Understanding
Solidify your learning with the interactive assessment directly below this lesson.
Concept Quiz & Questions
List slices
Check your understanding of list slices.
What is printed?
items = [1, 2, 3, 4]print(items[1:3])What is printed?
items = [1, 2, 3]items[:2] = [9]print(items)What is printed?
items = [1, 2]part = items[:]part[0] = 8print(items)Which expression selects the final two items?