Python Using List Slicing to Extract Sublist

Document 对象参考手册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. Slicing uses square brackets[]and colon:to specify the start index, end index, and step.

Suppose we have a listmy_list = [0, 1, 2, 3, 4, 5, 6, 7, 8, 9], and we want to extract some of its elements, we can use 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 explanation:

  • my_list[2:5]: This is a slicing operation,2is the start index,5is the end index. Slicing extracts elements from index2to index5before (i.e., excluding index5).
  • sub_list: This is the new list obtained after slicing.

Output result:

[2, 3, 4]

Document 对象参考手册Python3 Examples

Other Extensions