← Go Back

How to Get a Subset of a List, Tuple or String

Since lists, tuples and strings are ordered collections of objects, they support an operation called slicing. Slicing lets you get a subset of a collection by giving start and end indexes between square brackets and separated by colons:

>>> languages = ["Python", "C", "C++", "Java", "Elixir", "Rust"]
>>> languages[2:4]
['C++', 'Java']

When any of the indexes are omitted, Python uses reasonable defaults:

>>> languages[1:]  # All elements except the first.
['C', 'C++', 'Java', 'Elixir', 'Rust']

This code is similar to languages[1:len(languages)].

Indices can also be negative, to indicate positions from the end of the list (i.e., from right to left.)

>>> languages[:-1]  # All elements except the last one.
['Python', 'C', 'C++', 'Java', 'Elixir']

A third index indicates the interval or step by which items are retrieved. The default is 1, so every item is included in the result.

>>> languages[::2]  # Fetch elements every 2 steps.
['Python', 'C++', 'Elixir']
>>> list(range(1, 11))[::2]
[1, 3, 5, 7, 9]

Since this third index can also be a negative number, the following code returns the elements from right to left.

>>> languages[::-1]
['Rust', 'Elixir', 'Java', 'C++', 'C', 'Python']

The procedure is the same for strings. Each character is considered an item:

>>> s = "Hello world!"
>>> s[5:10]

lists tuples strings slicing

🐍 You might also find interesting: