List slicing in Python allows us to extract a portion of a list, creating a new list.
The syntax for list slicing is list[start:stop:step], where:
- start is the index where the slice begins (inclusive).
- stop is the index where the slice ends (exclusive).
- step is the step size used to iterate through the list.
Problem to understand list slicing:
Python
# Create a list of numbers
numbers = [0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
# Extract a slice from index 2 to 5 (exclusive)
slice1 = numbers[2:5]
# Extract a slice from the beginning up to index 7 (exclusive)
slice2 = numbers[:7]
# Extract a slice from index 3 to the end
slice3 = numbers[3:]
# Extract every second element from index 1 to 8 (exclusive)
slice4 = numbers[1:8:2]
# Print the slices
print("Slice 1:", slice1)
print("Slice 2:", slice2)
print("Slice 3:", slice3)
print("Slice 4:", slice4)
Code explanation:
- Created a list named
numbers
with integers from 0 to 9. - Used list slicing to create four different slices:
slice1
: Contains elements from index 2 to 4 (excluding 5).slice2
: Contains elements from the beginning up to index 6 (excluding 7).slice3
: Contains elements from index 3 to the end.slice4
: Contains every second element from index 1 to 7 (excluding 8).
- Printed out the resulting slices.
Output:
Output
Slice 1: [2, 3, 4]
Slice 2: [0, 1, 2, 3, 4, 5, 6]
Slice 3: [3, 4, 5, 6, 7, 8, 9]
Slice 4: [1, 3, 5, 7]