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.
|
|
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:
|
|
- 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:
|
|
The first 3 elements of a list
To display the first three elements of the list, we can use slicing with the following parameters:
|
|
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:
|
|
The printed result will be [7, 8, 9, 10]
.
Text in reverse order
Assume we have the following string:
|
|
The printed result will be !dlroW ,olleH
.
Every other element
Assume we have the following string:
|
|
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:
|
|
The printed result will be [3, 5, 7]
.