Python Use List Slicing to Extract a Sublist
In Python, list slicing is a very powerful feature that allows you to extract a portion of elements from a list to form a new sublist. The slicing operation uses square brackets [] and a colon : to specify the start index, end index, and step.
Suppose we have a list my_list = [0, 1, 2, 3, 4, 5, 6, 7, 8, 9], and we want to extract a portion of its elements using slicing.
Example
my_list
=
[
0
,
1
,
2
,
3
,
4
,
5
,
6
,
7
,
8
,
9
]
Extract elements from index 2 to 5 (excluding index 5)
sub_list
=
my_list
[
2
:
5
]
(
sub_list
)
Code analysis:
my_list[2:5]: This is a slicing operation,2is the start index,5is the end index. The slicing operation extracts elements from index2up to but not including index5(i.e., not including the element at index5).sub_list: This is the new list obtained after the slicing operation.
Output result:
[2, 3, 4]
Python3 Examples