Skip to Content
PythonPython Data Types3. Indexing & Slicing

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.

Indexing in Python

Python supports two styles of indexing, depending on whether you want to count forwards or backwards:

Counting Forwards

  • Starts at 0 for the very first item.
  • The second item is at index 1, the third is at index 2, and so on.
  • The last item is at index length - 1.

Example

Output:

First character (index 0): P
Fifth character (index 4): o

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: 10
Last item: True
Middle 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 to 0.
  • 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 to 1.

Let us explore the different ways to slice a sequence using our interactive tab menu:

Basic Slicing

Extracts a simple range of elements.


Example

Output:

Slice [2:5] result: [2, 3, 4]

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!

Last updated on