Module 8 · Python Data Structures — topic 5 of 22
Slicing
Take sub-lists with items[start:stop:step], copy and reverse lists, and use slice assignment to replace, insert or delete several items at once.
Learning objectives
- Extract sub-lists with slices
- Copy and reverse lists with slicing
- Replace, insert and delete ranges with slice assignment
Definition
Take sub-lists with items[start:stop:step], copy and reverse lists, and use slice assignment to replace, insert or delete several items at once.
Introduction
Slicing works on lists exactly as on strings: items[1:4] returns a new list with the items at indexes 1, 2 and 3. Because lists are mutable, slices can also appear on the left of an assignment to change several items at once.
Why it matters
Slices extract the top three results, all but the header row, the most recent ten entries, or every second item, in a single expression. Slice assignment edits parts of a list without loops.
Detailed explanation
items[start:stop] includes start and excludes stop; omitted values mean the beginning or end.
items[-n:] gives the last n items; items[:-1] everything except the last.
items[::2] takes every second item; items[::-1] returns a reversed copy.
items[:] is a shallow copy: a new list containing the same item objects.
Slicing never raises IndexError; out-of-range positions are clipped.
Slice assignment replaces a range with the items of another iterable, and the lengths may differ: items[1:3] = ["a", "b", "c"] grows the list.
items[i:i] = [x] inserts at position i, and items[i:j] = [] or del items[i:j] removes a range.
Syntax
- Reading a slice returns a new list.
- Assigning to a slice changes the list in place.
- del removes the items in a slice.
Code examples
Reading slices
[20, 30, 40] [10, 20] [50, 60] [10, 30, 50] [60, 50, 40, 30, 20, 10]
Slice assignment
['a', 'X', 'Y', 'Z', 'd', 'e'] ['start', 'a', 'X', 'Y', 'Z', 'd', 'e'] ['start', 'a', 'X', 'Y', 'Z']
More examples
Working with ranked results
Top 3: [99, 95, 88] Rest: [84, 77, 72, 61] Bottom 2: [72, 61] ['name', 'mark'] 3 data rows Last five entries: [8, 9, 10, 11, 12]
Step-by-step explanation
- sorted(..., reverse=True) ranks the scores from highest to lowest.
- [:3], [3:] and [-2:] split the ranking into the top three, the rest and the bottom two.
- rows[1:] skips the header row of the data.
- recent[-5:] keeps only the five newest entries after each append.
Expected output
Running “Working with ranked results” prints exactly:
Practical applications
- Search pages show results[(page - 1) * 10 : page * 10] for each page.
- Data scripts skip header rows with rows[1:].
- Chat apps keep the most recent messages with messages[-50:].
Best practices
- Use slices to split data into named parts.
- Use [::-1] or reversed() for reversed views.
- Use slice assignment sparingly; methods like insert() and remove() are often clearer.
Common mistakes
Assigning a single value to a slice
Avoid
Prefer
Slice assignment needs an iterable; a plain int raises TypeError.
Assuming [:] makes a deep copy
Avoid
Prefer
[:] copies the outer list only; inner lists are still shared (Module 17).
Key takeaways
- items[start:stop:step] returns a new list.
- [:] copies and [::-1] reverses.
- Slice assignment and del can replace, insert or delete ranges in place.
Try it yourself
- 1Given a list of 12 monthly sales, print the first quarter and the last quarter using slices.
- 2Replace the middle three items of a 5-item list with a single item using slice assignment.
Finished reading? Mark it complete to update your dashboard.
Suggested practice
1 question test this exact topic. Answers and explanations are revealed after you submit.
- BeginnerWhat is printed?