How to slice sequences in Python

Pratik Choudhari

Slicing of sequences in Python is a crucial and easy to learn concept. In this article we will see different types of slicing and understand them with examples.

About Sequences

Sequence data structures are iterable and the elements of a sequence can be accessed via their index except set and frozenset.

Slicing relies on indexing to specify the portion of sequence to extract data from.

As slicing is allowed only for indexable sequences the following data structures are eligible:

The Slice Notation:

my_list[start: end: step]

Alternatively, slice() can be used

my_list[slice(start, end, step)]

Here, start, end and step are integers. start defines the index to start slicing from and continue till index end - 1(end index is excluded).

There are multiple variations of using slice notation:

Examples:

1. With start and end

colors = ["red", "green", "blue", "yellow", "cyan"] print(colors[1: 3])

Output:

['green', 'blue']

2. With end only

colors = ["red", "green", "blue", "yellow", "cyan"] print(colors[: 4])

Output:

['red', 'green', 'blue', 'yellow']

3. With start only

colors = ["red", "green", "blue", "yellow", "cyan"] print(colors[2:])

Output:

['blue', 'yellow', 'cyan']

The step in Slicing

step defines the number of index to move forward while slicing an object. If step is not specified, default value is taken as 1 which means move without skipping any index.

Example:

colors = ["red", "green", "blue", "yellow", "cyan"] print(colors[: 4: 2])

Output:

['red', 'blue']

With a string:

alphabets = "abcdefghijklmnopqrstuvwxyz" print(alphabets[::2])

Output:

acegikmoqsuwy

FREE VS Code / PyCharm Extensions I Use

✅ Write cleaner code with Sourcery, instant refactoring suggestions: Link *

* This is an affiliate link. By clicking on it you will not have any additional costs, instead you will support me and my project. Thank you! 🙏

Check out my Courses