Learn how to use Python list slicing to extract and manipulate parts of lists. This guide provides clear explanations and examples for efficient coding.
Slicing a list in Python means extracting a portion (or subsequence) of the list using a specific syntax:
Syntax:
list[start:stop:step]
start: index to begin slicing (inclusive)
stop: index to end slicing (exclusive)
step: how many elements to skip (default is 1)
Examples:
numbers = [10, 20, 30, 40, 50, 60, 70]
1. Get elements from index 1 to 4:
numbers[1:5] # [20, 30, 40, 50]
2. Get every second element:
numbers[::2] # [10, 30, 50, 70]
3. Reverse the list:
numbers[::-1] # [70, 60, 50, 40, 30, 20, 10]
4. From index 3 to end:
numbers[3:] # [40, 50, 60, 70]
5. From start to index 4:
numbers[:5] # [10, 20, 30, 40, 50]
📺 Video Tutorial: List Slicing
The video explains how to modify a list by replacing multiple elements with a single element.
This video covers:
✔️ A list called "list1" is created with five integers [00:07].
✔️ The second, third, and fourth elements of the list (98, 23, and 70) are selected using slice notation [00:13].
✔️ These elements are replaced with the single element 20 [00:23].