No history yet

Introduction to Slicing

Extracting Pieces with Slicing

Often, you don't need an entire sequence, just a piece of it. Whether you're working with a string, a list, or a tuple, Python has a clean way to grab a subsequence. This technique is called slicing.

Slicing lets you select a range of items by providing two indices: a starting point and an ending point. The syntax looks like this:

sequence[start:stop]

Here's the key rule to remember: the slice includes the element at the start index but goes up to, and does not include, the element at the stop index. Think of it as a half-open interval in math, [start,stop)[start, stop). Let's visualize this with a list of letters.

Slicing in Action

Let's start with a string. Suppose we want to extract the word "quick" from the sentence below. We know 'q' is at index 4 and the character after 'k' (a space) is at index 9. So, our slice will be [4:9].

sentence = "The quick brown fox"
word = sentence[4:9]
print(word)
# Output: quick

Python also provides some handy shortcuts. If you omit the start index, the slice automatically begins from the start of the sequence. If you omit the stop index, it goes all the way to the end.

# From the beginning up to index 3
first_part = sentence[:3]
print(first_part)
# Output: The

# From index 16 to the end
last_part = sentence[16:]
print(last_part)
# Output: fox

This exact same logic applies to lists and tuples. The syntax is identical, and the result is a new sequence of the same type.

# Slicing a list
numbers_list = [10, 20, 30, 40, 50, 60]
middle_list = numbers_list[2:5] 
print(middle_list)
# Output: [30, 40, 50]

# Slicing a tuple
colors_tuple = ('red', 'green', 'blue', 'yellow', 'purple')
first_two_colors = colors_tuple[:2]
print(first_two_colors)
# Output: ('red', 'green')

Slicing always creates a new, smaller copy of a sequence. It never modifies the original string, list, or tuple.

Now, let's test your understanding with a few questions.

Quiz Questions 1/5

Given the list letters = ['a', 'b', 'c', 'd', 'e'], what is the result of letters[1:4]?

Quiz Questions 2/5

True or False: The slice my_sequence[2:5] will include the element at index 5.

Slicing is a fundamental skill in Python for accessing and manipulating parts of your data without needing complex loops. As you continue, you'll find yourself using it constantly.