S is for slicing - Python A to Z
Code in this blog post was written with versions: Python: 3.14
Python A-Z is a blog series about Python. Each day, I share insights, ideas and examples for different parts of Python development that match with the letter of the day. Blaugust is an annual blogging festival in August where the goal is to write a blog post every day of the month.
Another 101 level primer day! Today, I write about slicing lists. Python has a very nice syntax for it, albeit one that can take a bit to get comfortable with.
Let’s start with index access
To access a single item in a list, you use
[i] where
i is the index:
pokemon = ['Pikachu', 'Snorlax', 'Bulbasaur']
print(pokemon[0]) # Pikachu
print(pokemon[1]) # Snorlax
print(pokemon[2]) # Bulbasaur
If you’re new to programming, it’s important to note that the indexing starts at 0, not 1. This is common for a lot of programming languages but not universal.
If you try to access an index that is larger than the last available index,
you’ll run into an IndexError :
pokemon = ['Pikachu', 'Snorlax', 'Bulbasaur']
print(pokemon[4]) # IndexError: list index out of range
If you use a negative index, Python will count from the end:
pokemon = ['Pikachu', 'Snorlax', 'Bulbasaur']
print(pokemon[-1]) # Bulbasaur
print(pokemon[-2]) # Snorlax
print(pokemon[-3]) # Pikachu
print(pokemon[-4]) # IndexError: list index out of range
Here, the last element is at index
-1 and the first one at
0 - len(pokemon) .
Slicing
“Slicing” refers to accessing a sublist from a list rather than an individual element.
The syntax has three parts, all optional:
list[start:stop:step]
For example, we can create a new list that has all but the first element:
pokemon = ['Pikachu', 'Snorlax', 'Bulbasaur']
first = pokemon[0] # 'Pikachu'
rest = pokemon[1:] # ['Snorlax', 'Bulbasaur']
# is same as
rest = pokemon[1:3]
Slicing a list does not change the original! It creates a new copy with the elements we want.
As you can see in the example, the parameters of a slice are optional. If we
want everything until the end, we can leave out
stop. If we want everything from the
start, we can leave out start:
pokemon = ['Pikachu', 'Snorlax', 'Bulbasaur']
all_but_last = pokemon[:2] # pokemon = ['Pikachu', 'Snorlax']
# is same as
all_but_last = pokemon[0:2]
The stop parameter is
exclusive, meaning we don’t include it.
Since both of them are optional, we can create a copy of a list with
pokemon = ['Pikachu', 'Snorlax', 'Bulbasaur']
a_copy = pokemon[:]
print(a_copy) # ['Pikachu', 'Snorlax', 'Bulbasaur']
This will slice everything from the beginning to the end of a list.
We can use negative indices here as well:
pokemon = ['Pikachu', 'Snorlax', 'Bulbasaur']
all_but_last = pokemon[:-1]
print(all_but_last) # ['Pikachu', 'Snorlax']
The last parameter is step and it allows
us to create lists where we skip items or move backwards:
numbers = [0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
# Take every other element
evens = numbers[::2] # [0, 2, 4, 6, 8, 10]
odds = numbers[1::2] # [1, 3, 5, 7, 9]
# Take every third element
every_third = numbers[::3] # [0, 3, 6, 9]
# Reverse a list
countdown = numbers[::-1] # [10, 9, 8, 7, 6, 5, 4, 3, 2, 1, 0]
You can then mix and match these to achieve all sorts of slices.
You can also create slices up front with the built-in slice function:
reverse = slice(None, None, -1)
print(numbers[rev]) # [10, 9, 8, 7, 6, 5, 4, 3, 2, 1, 0]
evens = slice(0, None, 2)
print(numbers[evens]) # [0, 2, 4, 6, 8, 10]
I can’t remember a single time I would have used
slice but it does help with one of my
favourites I’ll repeat many times this month: giving names to ideas is
powerful.
No IndexErrors!
A key difference between access by index and slicing is that there are no
IndexErrors with slicing.
numbers = [0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
print(numbers[6:100]) # [6, 7, 8, 9, 10]
When slicing with an end index too large, Python simply goes as far as it can.
This can sometimes be a curse and a blessing as you can’t figure out the
length of a new list based on the
stop parameter.
Use REPL to experiment and learn
Yesterday I wrote about Python’s REPL. It’s really good for learning a new mechanic like this. You can start the REPL and keep on tinkering. Create lists, slice them in any and every way you can imagine and see if the results match your expectations.
If something above resonated with you, let's start a discussion about it! Email me at juhis@hamatti.org and share your thoughts. This year, I want to have more deeper discussions with people from around the world and I'd love if you'd be part of that.