Contents

The Slicing in Python: Usage and Examples

1/ Sequences

In Python, sequences are data types that represent an ordered collection of elements. The most common sequence types are lists, tuples, and strings.

1
2
3
a_list = ["a", "b", "c", "d"]
a_tuple = ("a", "b", "c", "d")
a_string = "abcd"


2/ Slicing

Slicing in Python is a feature that allows you to extract a sub-sequence from a sequence. This can be very useful for accessing specific parts of a sequence. Slicing uses three parameters:

1
sequence[start:stop:step]
  • The first parameter is the start index, which is included in the sub-sequence.
  • The second parameter is the stop index, which is excluded from the sub-sequence.
  • The third parameter step (optional) indicates the frequency at which elements should be extracted from the sequence.


3/ Examples

Assume we have the following list:

1
my_list = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]

The first 3 elements of a list

To display the first three elements of the list, we can use slicing with the following parameters:

1
2
print(my_list[:3])
>>> [1, 2, 3]

The printed result will be [1, 2, 3].


The last 4 elements of a list

To display the last four elements of the list, we can use slicing with the following parameters:

1
2
print(my_list[-4:])
>>> [7, 8, 9, 10]

The printed result will be [7, 8, 9, 10].


Text in reverse order

Assume we have the following string:

1
2
3
texte = "Hello, World!"
print(texte[::-1])
>>> "!dlroW ,olleH"

The printed result will be !dlroW ,olleH.


Every other element

Assume we have the following string:

1
2
3
my_list = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
print(my_list[::2])
>>> [1, 3, 5, 7, 9]

The printed result will be [1, 3, 5, 7, 9].


Example of using slicing with all three parameters

To extract elements from the list starting from index 2 (included), up to index 8 (excluded), and using a step of 2, we can use slicing as follows:

1
2
3
my_list = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
print(my_list[2:8:2])
>>> [3, 5, 7]

The printed result will be [3, 5, 7].