Slicing lists & strings

RoadmapsPython

Overview

Slicing lets you extract a portion of a sequence (like a list, string, or tuple) using the syntax `seq[start:stop:step]`. - **start**: The index to begin at (inclusive). Defaults to 0. - **stop**: The index to end before (exclusive). Defaults to the length of the sequence. - **step**: The stride. Defaults to 1. Think of the indices as pointing *between* elements (fence-posts). `a[1:3]` extracts from the first fence-post up to the third. Because `stop` is exclusive, `a[:n]` gives you the first `n` elements, and `a[1:]` gives you everything except the first element. Negative indices count from the end. `a[-3:]` gives the last 3 elements. `a[:-1]` gives everything *except* the last element. The `step` argument lets you skip elements or reverse. `a[::2]` gets every second element. `a[::-1]` reverses the sequence. Crucially, a slice creates a **shallow copy**. `copy = a[:]` makes a new outer list. Modifying `copy[0]` won't affect `a`, but if `a` contains nested lists, both slices point to the same inner lists.

Slicing is heavily used in algorithmic code. Need to check if a string is a palindrome? `s == s[::-1]`. Need to skip the header row of a CSV? `rows[1:]`. Need to implement pagination? `results[page*10:(page+1)*10]`. It's idiomatic, fast, and prevents off-by-one loop errors.

Where used: Extracting prefix/suffix of strings, Reversing sequences, Copying matrix rows

Why learn this

Code walkthrough

data = [0, 10, 20, 30, 40, 50]
first_three = data[:3]
last_two = data[-2:]
reversed_copy = data[::-1]
print(first_three, last_two, reversed_copy)

Focus: Notice how `[:3]` gets indices 0, 1, 2. `[-2:]` grabs the last two elements. `[::-1]` uses a negative step to reverse.

Aha moment

a = [1, 2, 3]
b = a[:]
b[0] = 99
print(a)

Prediction: What does this print?

Common guess: [99, 2, 3]

It prints `[1, 2, 3]`. `a[:]` creates a new shallow copy. Modifying the slots of `b` does not affect `a`. (However, if they contained nested lists, mutating the *contents* of a nested list would affect both).

Common mistakes

Glossary

slice
A subset of a sequence extracted using `[start:stop:step]` notation. It always returns a new sequence (a shallow copy) of the same type.

Recall questions

Understanding checks

What does this slice output?

yth

Indices 1, 2, and 3 correspond to 'y', 't', and 'h'. The stop index 4 ('o') is exclusive.

What does this print?

[]

Slicing past the end of a list does not raise an IndexError; it simply returns an empty list.

Practice tasks

Extract the middle

Modify the `get_middle` function to return a slice containing all elements except the first and the last.

Continue learning

Previous: Lists: indexing, slicing, methods

Previous: Strings & string methods

Next: Shallow vs Deep Copy

Return to Python Roadmap