When writing a Python program you might want to access multiple elements in a list. In this scenario, Python list slicing can be very useful.
With Python’s list slicing notation you can select a subset of a list, for example, the beginning of a list up to a specific element or the end of a list starting from a given element. The slicing notation allows specifying the start index, stop index, and interval between elements (step) to select.
Slicing is a topic that can be a bit confusing for Python beginners and in this article, I will help you understand slicing based on my personal experience of using it in several Python applications.
Let’s see some examples of list slicing!
What Is List Slicing in Python?
In Python, you can use the colon character( : ) within square brackets to print part of a list (this is called slicing).
The first step to using slicing with a Python list is to understand the syntax for slicing:
list_slice = original_list[start:stop:step]
The first important concept to know is that when you apply the slicing operator to a list you get back another list.
The syntax of slicing in Python supports the following arguments:
- start: the start index (inclusive)
- stop: the stop index (exclusive)
- step: the interval between elements returned in the slice
Based on my experience, one of the confusing aspects of slicing can be the fact that the start index is inclusive and the stop index is exclusive.
This is something you will have to remember and get used to in order to make sure you select the correct subset of a list.
6 Examples of List Slicing in Python
Let’s go through a few examples to explain how you can use the start, stop, and step arguments in the slicing notation.
Let’s take a list that contains the first 10 numbers of the Fibonacci sequence:
fibonacci_sequence = [0, 1, 1, 2, 3, 5, 8, 13, 21, 34]