Python Extract Elements in a Given Range from a List
Suppose we have a list my_list = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10], we want to extract the elements whose indices range from 2 to 6 (including indices 2 and 6). We can do this with Python's slice operation.
Example
my_list
=
[
1
,
2
,
3
,
4
,
5
,
6
,
7
,
8
,
9
,
10
]
extracted_elements
=
my_list
[
2
:
7
]
(
extracted_elements
)
Code analysis:
my_list[2:7]: This is Python's slice operation; it means the elements starting at index 2 (inclusive) and ending at index 7 (exclusive). It therefore extracts the elements at indices 2, 3, 4, 5 and 6.print(extracted_elements): Print the extracted elements.
Output result:
Example
[
3
,
4
,
5
,
6
,
7
]
Python3 Examples