Indexing Patterns
Slice Notation
Slice notation is a powerful way to extract subsequences from Python sequences:
## Basic slice syntax: [start:end:step]
numbers = [0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
## Simple slicing
print(numbers[2:5]) ## Outputs: [2, 3, 4]
print(numbers[:4]) ## Outputs: [0, 1, 2, 3]
print(numbers[6:]) ## Outputs: [6, 7, 8, 9]
Advanced Slicing Techniques
Reverse Slicing
## Reverse a sequence
numbers = [0, 1, 2, 3, 4, 5]
print(numbers[::-1]) ## Outputs: [5, 4, 3, 2, 1, 0]
Step Slicing
## Extract elements with custom step
numbers = [0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
print(numbers[1:8:2]) ## Outputs: [1, 3, 5, 7]
Indexing Patterns Flowchart
graph TD
A[Start Indexing] --> B{Slice Type}
B -->|Simple Slice| C[start:end]
B -->|Reverse Slice| D[start:end:negative_step]
B -->|Step Slice| E[start:end:step]
C --> F[Extract Subsequence]
D --> G[Reverse Sequence]
E --> H[Extract with Custom Interval]
Common Indexing Patterns
Pattern |
Syntax |
Description |
Example |
Full Slice |
[:] |
Entire sequence |
list[:] |
Reverse |
[::-1] |
Reverse order |
[5,4,3,2,1] |
Skip Elements |
[::2] |
Every second element |
[0,2,4,6] |
Practical Examples
## Multiple indexing techniques
text = "LabEx Python Tutorial"
## Extract specific parts
print(text[0:6]) ## Outputs: 'LabEx'
print(text[7:13]) ## Outputs: 'Python'
print(text[::-1]) ## Outputs: 'lairotuT nohtyP xEbaL'
LabEx Pro Tip
Mastering slice notation can significantly improve your Python coding efficiency. Practice different slicing techniques to become proficient.
Error Handling in Indexing
def safe_slice(sequence, start=None, end=None, step=None):
try:
return sequence[start:end:step]
except Exception as e:
print(f"Indexing error: {e}")
return None