Slicing

Published

2023-08-02

Slicing

Python supports a powerful means for extracting data from a sequence (string, list or tuple) called slicing.

Basic slicing

We can take a slice through some sequence by specifying a range of indices.

>>> un_security_council = ['China', 'France', 'Russia', 'UK', 
...                        'USA', 'Albania', 'Brazil', 'Gabon',
...                        'Ghana', 'UAE', 'India', 'Ireland', 
...                        'Kenya', 'Mexico', 'Norway']

Let’s say we just wanted the permanent members of the UN Security Council (these are the first five in the list). Instead of providing a single index within brackets, we provide a range of indices, in the form <sequence>[<start>:<end>].

>>> un_security_council[0:5]
['China', 'France', 'Russia', 'UK', 'USA']

“Hey! Wait a minute!” you say, “We provided a range of six indices! Why doesn’t this include ‘Albania’ too?”

Reasonable question. Python treats the ending index as its stopping point, so it slices from index 0 to index 5 but not including the element at index 5! This is the Python way, as you’ll see with other examples soon. It does take a little getting used to, but when you see this kind of indexing at work elsewhere, you’ll understand the rationale.

What if we wanted the non-permanent members whose term ends in 2023? That’s Albania, Brazil, Gabon, Ghana, and UAE.

To get that slice we’d use

>>> un_security_council[5:10]
['Albania', 'Brazil', 'Gabon', 'Ghana', 'UAE']

Again, Python doesn’t return the item at index 10; it just goes up to index 10 and stops.

Some shortcuts

Python allows a few shortcuts. For example, we can leave out the starting index, and Python reads from the start of the list (or tuple).

>>> un_security_council[:10]
['China', 'France', 'Russia', 'UK', 'USA', 
 'Albania', 'Brazil', 'Gabon', 'Ghana', 'UAE']

By the same token, if we leave out the ending index, then Python will read to the end of the list (or tuple).

>>> un_security_council[10:]
['India', 'Ireland', 'Kenya', 'Mexico', 'Norway']

Now you should be able to guess what happens if we leave out both start and end indices.

>>> un_security_council[:]
['China', 'France', 'Russia', 'UK', 'USA', 
 'Albania', 'Brazil', 'Gabon', 'Ghana', 'UAE', 
 'India', 'Ireland', 'Kenya', 'Mexico', 'Norway']

We get a copy of the entire list (or tuple)!

Guess what these do:

  • un_security_council[-1:]
  • un_security_council[:-1]
  • un_security_council[5:0]
  • un_security_council[5:-1]

Specifying the stride

Imagine you’re on a stepping-stone path through a garden. You might be able to step one stone at a time. You might be able to step two stones at a time—skipping over every other stone. If you have long legs, or the stones are very close together, you might be able to step three stones at a time! We call this step size or stride.

In Python, when specifying slices we can specify the stride as a third parameter. This comes in handy if we only want values at odd indices or at even indices.

The syntax is <sequence>[<start>:<stop>:<stride>].

Here are some examples:

>>> un_security_council[::2]  # only even indices
['China', 'Russia', 'USA', 'Brazil', 'Ghana', 
 'India', 'Kenya', 'Norway']
>>> un_security_council[1::2]  # only odd indices
['France', 'UK', 'Albania', 'Gabon', 'UAE', 
 'Ireland', 'Mexico']

What happens if the stride is greater than the number of elements in the sequence?

>>> un_security_council[::1000]
['China']

Can we step backward? Sure!

>>> un_security_council[-1::-1]
['Norway', 'Mexico', 'Kenya', 'Ireland', 'India', 
 'UAE', 'Ghana', 'Gabon', 'Brazil', 'Albania', 
 'USA', 'UK', 'Russia', 'France', 'China']

Now you know one way to get the reverse of a sequence. Can you think of some use cases for changing the stride?

Original author: Clayton Cafiero < [given name] DOT [surname] AT uvm DOT edu >

No generative AI was used in producing this material. This was written the old-fashioned way.

This material is for free use under either the GNU Free Documentation License or the Creative Commons Attribution-ShareAlike 3.0 United States License (take your pick).