No history yet

Python Sequence Slicing

Slicing Sequences

You already know how to access a single item from a list or string using its index. But what if you need a range of items—a subsection of the sequence? Python's slicing syntax is a powerful way to do just that. It works on any sequence type, including lists, strings, and tuples.

The colon (:) operator accepts three optional parameters: Syntax:sequence[start : end : step] Parameters: start: Starting index of the slice (can be negative or positive). end: Ending index of the slice (exclusive, not included). step: Number of steps to move (use -1 to reverse).

Let's start with a simple example. We have a list of numbers representing sensor readings.

readings = [10, 20, 30, 40, 50, 60, 70, 80]

# Get a slice from index 2 up to index 5
subset = readings[2:5]

print(subset) # Output: [30, 40, 50]

The Inclusive Start, The Exclusive Stop

The most important rule of slicing is how the boundaries work. The start index is inclusive, meaning the item at that position is included in the result. The stop index is exclusive, meaning the slice goes up to, but does not include, the item at that position.

Think of it as selecting items from start to stop - 1. This might seem strange, but it's a common convention in programming because it makes certain calculations easier. For example, the length of the slice seq[a:b] is simply b - a. This follows the principle of zero-based indexing that you're already familiar with.

This principle applies to strings just as it does to lists.

file_name = "report_2024_final.csv"

# Extract the year
year = file_name[7:11]
print(year) # Output: '2024'

# Extract the file type
extension = file_name[18:21]
print(extension) # Output: 'csv'

Jumping with Step

The third parameter, step, lets you skip elements. By default, the step is 1, which means you move from one element to the next. If you set it to 2, you'll take every second element.

numbers = [0, 1, 2, 3, 4, 5, 6, 7, 8, 9]

# Get all even numbers
evens = numbers[0:10:2] # Start at 0, go to 10, step by 2
print(evens) # Output: [0, 2, 4, 6, 8]

# You can omit start and stop if you want the whole sequence
all_evens = numbers[::2]
print(all_evens) # Output: [0, 2, 4, 6, 8]

A negative step value is a neat trick for reversing a sequence. A step of -1 starts from the end and moves backward. This is a common Python idiom, celebrated for its clarity and conciseness, reflecting the design philosophy of Python's creator, Guido van Rossum

message = "desserts"

# Reverse the string
reversed_message = message[::-1]

print(reversed_message) # Output: 'stressed'

When you use a negative step, the roles of start and stop are also reversed. The start index should be greater than the stop index.

numbers = [0, 1, 2, 3, 4, 5, 6, 7, 8, 9]

# Slice from index 7 down to 2, stepping backwards
countdown = numbers[7:2:-1]

print(countdown) # Output: [7, 6, 5, 4, 3]

Common Patterns

Omitting the start or stop parameters tells Python to use the default values: the beginning of the sequence for start and the end for stop. This leads to some very useful shortcuts.

SliceBehavior
seq[:n]Gets the first n items.
seq[n:]Gets the items from index n to the end.
seq[:]Creates a shallow copy of the entire sequence.
seq[::2]Gets every other item.
seq[::-1]Reverses the sequence.

Slicing is a fundamental tool for data manipulation, whether you're cleaning up user input from a string or subsetting a large list of data for analysis. Mastering these patterns will make your code more efficient and more readable.

Ready to test your knowledge? Try these challenges.

Quiz Questions 1/6

What is the output of the following Python code?

readings = [10, 20, 30, 40, 50, 60]
print(readings[1:4])
Quiz Questions 2/6

In Python slicing sequence[start:stop], the item at the stop index is...

With these techniques, you can now precisely extract any subsection of a sequence you need.