Python Basics
Python Slices
1. What is a Slice?
A slice extracts a subset of a collection (list, string, tuple) and returns it as a new object — the original is never modified.
my_list = [2, 3, 4, 2, 1, 3, 2, 4, 3, 1]
new_list = my_list[0:2] # → [2, 3]
2. Slice Syntax
collection[start : stop : step]
| Parameter | Role | Default |
|---|---|---|
start |
Index to begin at (inclusive) | 0 (beginning) |
stop |
Index to end at (exclusive) | end of collection |
step |
How much to increment by | 1 |
Works exactly like
range(start, stop, step)— the stop value is never included.
Only the colon is required. Start, stop, and step are all optional.
3. Examples
Stop only
my_list[:4] # → first 4 elements (indices 0–3)
Start and stop
my_list[1:4] # → elements at indices 1, 2, 3
Start, stop, and step
my_list[1:6:2] # → indices 1, 3, 5
Step only (every other element)
my_list[::2] # → every other element from start to end
4. Negative Values
Just like negative indexing, slices support negative start, stop, and step.
Negative start
my_list[-4:] # → last 4 elements
Negative start and stop
my_list[-4:-1] # → 4th-last up to (not including) last element
Negative step (go backwards)
my_list[8:0:-1] # → from index 8 down to (not including) index 0
⚠️ When using a negative step, make sure
start > stop, otherwise you get an empty result.
5. Special Shortcuts
Copy a list / string / tuple
my_list[:] # → a brand new copy of the whole collection
Reverse a collection ⭐
my_list[::-1] # → reversed version
"hello"[::-1] # → "olleh"
(1, 2, 3)[::-1] # → (3, 2, 1)
This is one of the most useful slice tricks — memorize it!
6. Slices on Strings and Tuples
Slices work identically on strings and tuples.
String
s = "hello world"
s[::2] # → every other character: "hlowrd"
s[1:6:2] # → "el "
Tuple
tup = 1, 2, 3, 4, 5
tup[1:6:2] # → (2, 4)
tup[::-1] # → (5, 4, 3, 2, 1)
7. Slices Always Return a New Object
The original collection is never changed by a slice.
my_list = [1, 2, 3, 4, 5]
new_list = my_list[1:3] # → [2, 3]
# my_list is still [1, 2, 3, 4, 5]
Cheat Sheet
lst = [2, 3, 4, 2, 1, 3, 2, 4, 3, 1]
lst[:] # copy entire list
lst[:3] # first 3 elements
lst[2:] # from index 2 to end
lst[1:4] # indices 1, 2, 3
lst[1:6:2] # indices 1, 3, 5
lst[::2] # every other element
lst[::-1] # reverse the list
lst[-4:-1] # 4th-last up to (not including) last