Indexing and Slicing in Python
In Python, many data types are classified as sequences, which means they are ordered lists of items. The most popular sequence types are strings, lists, and tuples.
To work effectively with these collections, you need to know how to grab specific elements out of them. We do this through two essential techniques:
- Indexing: Accessing a single specific item at a known position.
- Slicing: Accessing a range or subsection of items.
Let us learn exactly how these systems work in Python!
Indexing: Grabbing Single Elements
Every item in a sequence is assigned a unique address or position number, called an index. Python uses a zero-based indexing system, meaning counting starts at 0 rather than 1.
Python supports two styles of indexing, depending on whether you want to count forwards or backwards:
Let us see this live in the editor below. We have pre-loaded a list of mixed values. Click “Run Code” to see the positions being printed:
Example
Output:
First item: 10Last item: TrueMiddle item: a
Watch Out for IndexError!
If you try to access an index position that does not exist (like trying to grab index 10 from a list containing only 5 elements), Python will immediately raise an IndexError. Always make sure your index values are within the actual range of the list!
Slicing: Grabbing Subsections
Slicing is a powerful, elegant feature that lets you extract a portion (a slice) of a sequence. The syntax for slicing uses brackets with three values separated by colons: [start:stop:step].
start: The index where you want the slice to begin (inclusive). If you leave this empty, Python defaults to0.stop: The index where the slice ends (exclusive). The slice extracts items up to, but not including, this position. If you leave this empty, Python goes all the way to the end.step: The increment value, which tells Python how many steps to hop forward. If you leave this empty, Python defaults to1.
Let us explore the different ways to slice a sequence using our interactive tab menu:
Slicing is Extremely Forgiving!
Unlike indexing, slicing will never raise an IndexError if your positions are outside the actual boundaries of the list. Python will simply stop at the physical edge of the list without complaining!