Private archive copy · Unofficial site · Content copyright belongs to Runoob Tutorial and the original authors · View Original

Python Use List Slicing to Extract a Sublist

Python Use List Slicing to Extract a Sublist

Document Object Reference Manual Python3 Examples

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

]

print

(

sub_list

)

Code analysis:

Output result:


[2, 3, 4]

Document Object Reference Manual Python3 Examples