Index Slicing Techniques
Basic Slicing Syntax
In Python, list slicing allows you to extract a portion of a list using the syntax list[start:end:step]
.
numbers = [0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
## Basic slicing examples
print(numbers[2:7]) ## Output: [2, 3, 4, 5, 6]
print(numbers[:4]) ## Output: [0, 1, 2, 3]
print(numbers[6:]) ## Output: [6, 7, 8, 9]
Slicing with Step Parameter
## Using step parameter
print(numbers[1:8:2]) ## Output: [1, 3, 5, 7]
print(numbers[::3]) ## Output: [0, 3, 6, 9]
Reverse Slicing Techniques
## Reversing a list
print(numbers[::-1]) ## Output: [9, 8, 7, 6, 5, 4, 3, 2, 1, 0]
print(numbers[5:2:-1]) ## Output: [5, 4, 3]
Slicing Visualization
graph LR
A[Slice Syntax] --> B[list[start:end:step]]
B --> C[start: beginning index]
B --> D[end: ending index (exclusive)]
B --> E[step: increment between indices]
Slicing Techniques Comparison
Technique |
Syntax |
Description |
Example |
Basic Slice |
list[start:end] |
Extract subset |
[1, 2, 3, 4] |
Full Slice |
list[:] |
Copy entire list |
[0, 1, 2, 3, 4] |
Reverse Slice |
list[::-1] |
Reverse list |
[4, 3, 2, 1, 0] |
Stepped Slice |
list[start:end:step] |
Skip elements |
[0, 2, 4] |
Advanced Slicing Examples
## Complex slicing scenarios
mixed_list = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
print(mixed_list[2:8:2]) ## Output: [3, 5, 7]
print(mixed_list[-3:]) ## Output: [8, 9, 10]
Key Takeaways
- Slicing provides powerful list manipulation
- Syntax follows
[start:end:step]
- Negative indices and steps work with slicing
LabEx encourages practicing these slicing techniques to master Python list manipulation.