Skip to main content
Editor

Python Slicing: Master Indexing for Strings, Lists, and Tuples

Beginner20 min6 exercises80 XP

Leer en españolЧитать на русскомLer em portuguêsอ่านภาษาไทย

0/6 exercises

Imagine a pizza cut into 8 slices, numbered 0 through 7. You don't always want the whole pizza. Sometimes you want slices 2 through 5. Sometimes you want every other slice. Sometimes you want the last three slices.

Python slicing lets you grab a portion of any sequence - a list, string, or tuple - using the same simple notation. It's one of the most elegant features in Python, and once you learn it, you'll use it everywhere.

In this tutorial, you'll learn the start:stop:step notation, how negative indices work, how to reverse any sequence, and the most common slicing patterns used by Python developers every day.

How Does Basic Slicing Work?

The basic slice syntax is sequence[start:stop]. It gives you items from the start index up to (but not including) the stop index. Think of it as a half-open interval.

Basic slicing with start:stop
fruits = ['apple', 'banana', 'cherry', 'date', 'elderberry']
# Get items at index 1, 2 (stops before 3)
print(fruits[1:3]) # ['banana', 'cherry']
# Get the first three items
print(fruits[0:3]) # ['apple', 'banana', 'cherry']
# Get items from index 2 to the end
print(fruits[2:5]) # ['cherry', 'date', 'elderberry']
Output
['banana', 'cherry']
['apple', 'banana', 'cherry']
['cherry', 'date', 'elderberry']

The "stop before" rule might feel odd at first. But it has a nice benefit: fruits[0:3] gives you exactly 3 items. For a simple [start:stop] slice where 0 <= start <= stop <= len(fruits), the number of items is stop - start.

Omitting start and stop
numbers = [10, 20, 30, 40, 50, 60]
# First three items (omit start)
print(numbers[:3]) # [10, 20, 30]
# Everything from index 3 onward (omit stop)
print(numbers[3:]) # [40, 50, 60]
# Copy the entire list (omit both)
copy = numbers[:]
print(copy) # [10, 20, 30, 40, 50, 60]
Output
[10, 20, 30]
[40, 50, 60]
[10, 20, 30, 40, 50, 60]

What Does the Step Parameter Do?

The full slice syntax is sequence[start:stop:step]. The step controls how far to jump between the items you take. A step of 2 takes every other item. A step of 3 takes every third item.

Using the step parameter
numbers = [0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
# Every other item
print(numbers[::2]) # [0, 2, 4, 6, 8]
# Every other item starting from index 1
print(numbers[1::2]) # [1, 3, 5, 7, 9]
# Every third item
print(numbers[::3]) # [0, 3, 6, 9]
# From index 1 to 7, every 2nd item
print(numbers[1:7:2]) # [1, 3, 5]
Output
[0, 2, 4, 6, 8]
[1, 3, 5, 7, 9]
[0, 3, 6, 9]
[1, 3, 5]

If you leave out start and stop, a positive step covers the whole sequence from the beginning to the end. A negative step flips those defaults and starts from the end, as you'll see below. You only need to specify them if you want to narrow the range.

How Do Negative Indices Work in Slicing?

Negative indices count from the end of the sequence. -1 is the last item, -2 is the second-to-last, and so on. You can use negative numbers in any part of the slice: start, stop, or step.

Slicing with negative indices
letters = ['a', 'b', 'c', 'd', 'e', 'f']
# Last three items
print(letters[-3:]) # ['d', 'e', 'f']
# Everything except the last two
print(letters[:-2]) # ['a', 'b', 'c', 'd']
# From second-to-last to last
print(letters[-2:]) # ['e', 'f']
Output
['d', 'e', 'f']
['a', 'b', 'c', 'd']
['e', 'f']

Negative indices are incredibly useful when you know you want items relative to the end. For example, my_list[-3:] always gives you the last three items, no matter how long the list is.

Negative slicing with strings
word = 'Python'
# Remove first and last character
print(word[1:-1]) # ytho
# Last 4 characters
print(word[-4:]) # thon
# First 2 characters
print(word[:2]) # Py
Output
ytho
thon
Py

How to Reverse a Sequence with [::-1]

A negative step tells Python to go backwards. The most common pattern is [::-1], which reverses the entire sequence. No start, no stop, step of -1 - just go from end to start.

Reversing with [::-1]
# Reverse a list
numbers = [1, 2, 3, 4, 5]
print(numbers[::-1]) # [5, 4, 3, 2, 1]
# Reverse a string
word = 'hello'
print(word[::-1]) # olleh
# Reverse a tuple
coords = (10, 20, 30, 40)
print(coords[::-1]) # (40, 30, 20, 10)
Output
[5, 4, 3, 2, 1]
olleh
(40, 30, 20, 10)

You can combine a negative step with start and stop to reverse just a portion. When using a negative step, the start should be greater than stop since you're going backwards.

Negative step with start and stop
numbers = [0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
# Reverse items from index 7 down to index 2 (not including 2)
print(numbers[7:2:-1]) # [7, 6, 5, 4, 3]
# Every other item, reversed
print(numbers[::-2]) # [9, 7, 5, 3, 1]
Output
[7, 6, 5, 4, 3]
[9, 7, 5, 3, 1]

Slicing Strings vs Lists vs Tuples

The same [start:stop:step] syntax works on all sequence types. The only difference is what you get back: slicing a list gives you a list, slicing a string gives you a string, and slicing a tuple gives you a tuple.

Slicing preserves the type
# Slicing a string -> string
name = 'Alexander'
print(name[0:4]) # Alex
print(type(name[0:4])) # <class 'str'>
# Slicing a list -> list
scores = [90, 85, 77, 92, 88]
print(scores[1:4]) # [85, 77, 92]
# Slicing a tuple -> tuple
point = (10, 20, 30, 40, 50)
print(point[::2]) # (10, 30, 50)
Output
Alex
<class 'str'>
[85, 77, 92]
(10, 30, 50)

Common Slicing Patterns Every Python Developer Should Know

Here are the slicing patterns you'll see and use most often. Think of this as your quick reference.

Six essential slicing patterns
data = ['a', 'b', 'c', 'd', 'e', 'f', 'g']
# First N items
print(data[:3]) # ['a', 'b', 'c']
# Last N items
print(data[-3:]) # ['e', 'f', 'g']
# Remove first item
print(data[1:]) # ['b', 'c', 'd', 'e', 'f', 'g']
# Remove last item
print(data[:-1]) # ['a', 'b', 'c', 'd', 'e', 'f']
# Middle items (remove first and last)
print(data[1:-1]) # ['b', 'c', 'd', 'e', 'f']
# Reverse the whole thing
print(data[::-1]) # ['g', 'f', 'e', 'd', 'c', 'b', 'a']
Output
['a', 'b', 'c']
['e', 'f', 'g']
['b', 'c', 'd', 'e', 'f', 'g']
['a', 'b', 'c', 'd', 'e', 'f']
['b', 'c', 'd', 'e', 'f']
['g', 'f', 'e', 'd', 'c', 'b', 'a']

You can also use slicing on the left side of an assignment to replace a section of a list. This is called slice assignment.

Slice assignment (lists only)
colors = ['red', 'green', 'blue', 'yellow', 'purple']
# Replace items at index 1 and 2
colors[1:3] = ['lime', 'sky']
print(colors) # ['red', 'lime', 'sky', 'yellow', 'purple']
# You can even replace with a different number of items
colors[1:3] = ['orange']
print(colors) # ['red', 'orange', 'yellow', 'purple']
Output
['red', 'lime', 'sky', 'yellow', 'purple']
['red', 'orange', 'yellow', 'purple']

Practice Exercises

Get the Middle Items
Write Code

Given the list animals, use slicing to print only the middle three items: ['cat', 'dog', 'elephant'].

animals = ['ant', 'bear', 'cat', 'dog', 'elephant', 'fox', 'giraffe']
# Print the middle three items using slicing
Predict the Slice Output
Predict Output

What does this code print? Think carefully about negative indices.

word = 'programming'
print(word[-4:])

Write a print() statement that produces the exact same output.

# Predict the output and write the matching print statement
print("?")
Extract Even-Indexed Items
Write Code

Given the list letters, use slicing with a step to print only the items at even indices (0, 2, 4, 6). The result should be ['a', 'c', 'e', 'g'].

letters = ['a', 'b', 'c', 'd', 'e', 'f', 'g']
# Print items at even indices using slicing
Reverse a Word
Write Code

Use slicing to reverse the string word and print the result. The output should be nohtyp.

word = 'python'
# Reverse the word using slicing and print it
Fix the Slicing Bug
Fix the Bug

This code tries to get the last three items from a list, but it's using the wrong slice. Fix the bug so it prints ['date', 'elderberry', 'fig'].

fruits = ['apple', 'banana', 'cherry', 'date', 'elderberry', 'fig']
# Bug: this doesn't get the last three items
last_three = fruits[3:0]
print(last_three)
Palindrome Checker
Write Code

Write a function called is_palindrome(text) that returns True if the text reads the same forwards and backwards, and False otherwise. Use slicing to reverse the string. Convert the text to lowercase first so the check is case-insensitive.

Test it with these calls:

print(is_palindrome('racecar'))
print(is_palindrome('Python'))
print(is_palindrome('Madam'))
def is_palindrome(text):
# Convert to lowercase and check if it equals its reverse
pass
print(is_palindrome('racecar'))
print(is_palindrome('Python'))
print(is_palindrome('Madam'))

Harder problems

More problems on this topic: Lists

Related Tutorials

Was this tutorial helpful?