Python List Slicing

In the last lesson, we learned about Python List Methods. Now let’s use slicing to take only the part of a list we need.

Let’s Talk About Taking Parts of a List

We have a list. Maybe it has 100 items. And we only want the first 10. Or the last 5. Or every second item.

We could write a loop and copy items one by one. But that is a lot of work.

Python gives us a much easier way. It is called slicing.

Slicing lets us take a piece of a list. We say where to start, where to stop, and how many to skip. And Python gives us that part as a new list.

We already learned about string slicing. List slicing works the same way. But because lists are mutable, there are some extra things we can do.

Let’s go through it.

The Basic Syntax of Python List Slicing

We use square brackets with a colon inside.

numbers = [10, 20, 30, 40, 50]
print(numbers[1:4])

Output

[20, 30, 40]

Let me explain.

  • 1 is the start index. It means start at index 1 (the second item, which is 20).
  • 4 is the end index. It means stop before index 4. So it includes indices 1, 2, and 3.
  • The result is a new list with those items.

The original list is not changed. Slicing creates a new list.

Leaving Out Start or End in Python List Slicing

If we leave out the start, it starts from the beginning.

print(numbers[:3])

Output

[10, 20, 30]

If we leave out the end, it goes to the end.

print(numbers[2:])

Output

[30, 40, 50]

If we leave out both, we get a copy of the whole list.

print(numbers[:])

Output

[10, 20, 30, 40, 50]

That is a common way to make a shallow copy of a list.

Negative Indices in Python List Slicing

We can use negative indices. They count from the end.

print(numbers[-3:-1])

Output

[30, 40]

Because -3 is the third from last (30), and -1 is the last (50). But the end is exclusive, so it stops before 50. So we get 30 and 40.

If we want the last two items, we can do:

print(numbers[-2:])

Output

[40, 50]

The Step in Python List Slicing

We can add a third number. That is the step. It tells Python how many items to skip.

print(numbers[::2])

Output

[10, 30, 50]

It takes every second item. Starting at index 0, then 2, then 4.

We can also use a negative step to go backwards.

print(numbers[::-1])

Output

[50, 40, 30, 20, 10]

That reverses the list. Very handy.

Slicing Creates a New List in Python

Let’s remember, slicing returns a new list. The original is not changed.

numbers = [1, 2, 3, 4, 5]
part = numbers[1:3]
print(part) # [2, 3]
print(numbers) # [1, 2, 3, 4, 5]

This is different from some list methods that change the list in place. Slicing always gives us a new list.

That also means if we modify the slice, the original is not affected.

part[0] = 99
print(part) # [99, 3]
print(numbers) # [1, 2, 3, 4, 5]

See? The original list is still the same.

Slice Assignment in Python — Changing a List with Slices

Because lists are mutable, we can assign to a slice. This changes the original list.

numbers = [1, 2, 3, 4, 5]
numbers[1:3] = [20, 30]
print(numbers)

Output

[1, 20, 30, 4, 5]

We replaced the items at index 1 and 2 with new values. The length of the slice and the new list do not have to match. Python will adjust the list size.

numbers = [1, 2, 3, 4, 5]
numbers[1:4] = [100]
print(numbers)

Output

[1, 100, 5]

We replaced three items with one item. The list shrank.

We can also insert items without removing any by using an empty slice.

numbers = [1, 2, 3]
numbers[1:1] = [10, 20]
print(numbers)

Output

[1, 10, 20, 2, 3]

That is like inserting at index 1.

Deleting Slices with del in Python

We can delete a slice using the del keyword.

numbers = [1, 2, 3, 4, 5]
del numbers[1:3]
print(numbers)

Output

[1, 4, 5]

It removed the items at index 1 and 2.

We can also delete the whole list contents.

del numbers[:]
print(numbers)

Output

[]

Python List Slicing: A Real-Life Example

Let’s say we have a list of daily temperatures for a week. And we want to analyze different parts.

temperatures = [72, 75, 68, 70, 74, 78, 80]
weekdays = temperatures[:5]
weekend = temperatures[5:]
print(f"Weekdays: {weekdays}")
print(f"Weekend: {weekend}")
# Reverse the list to see most recent first
recent_first = temperatures[::-1]
print(f"Most recent first: {recent_first}")

Output

Weekdays: [72, 75, 68, 70, 74]
Weekend: [78, 80]
Most recent first: [80, 78, 74, 70, 68, 75, 72]

That is a simple way to extract sublists.

Another Example — Updating a Slice

scores = [10, 20, 30, 40, 50]
# Replace the middle three scores
scores[1:4] = [25, 35, 45]
print(scores)

Output

[10, 25, 35, 45, 50]

That is very convenient for bulk updates.

Common Mistakes with Python List Slicing

Mistake 1: Forgetting That the End Is Exclusive

numbers = [1, 2, 3, 4, 5]
print(numbers[0:3])

Output

[1, 2, 3]

Not [1, 2, 3, 4]. Because index 3 is not included. To get the first four items, we use numbers[0:4].

Mistake 2: Using Out-of-Range Indices

Slicing is forgiving. If we go out of range, it just goes as far as it can.

print(numbers[0:100])

Output

[1, 2, 3, 4, 5]

No error. But if we use a single index that is out of range, we get an error.

print(numbers[100]) # Error!

Mistake 3: Thinking Slice Assignment Requires the Same Length

numbers = [1, 2, 3, 4, 5]
numbers[1:4] = [100]
print(numbers)

Output

[1, 100, 5]

The slice was length 3, the new list was length 1. Python adjusted. So no error. But sometimes that is not what we want. Let’s be careful.

Mistake 4: Using a Step of Zero

print(numbers[::0])

Output

ValueError: slice step cannot be zero

We cannot have a step of zero.

Next, we will learn about Python List Comprehensions and create new lists with concise expressions.