Practical Slicing Examples
Data Processing Scenarios
## Processing time series data
temperatures = [68, 70, 72, 65, 69, 75, 80, 82, 79, 77]
## Extract morning temperatures (first 4 hours)
morning_temps = temperatures[:4]
print("Morning Temperatures:", morning_temps)
## Extract afternoon temperatures (last 3 hours)
afternoon_temps = temperatures[-3:]
print("Afternoon Temperatures:", afternoon_temps)
2. Batch Processing
def process_data_batches(data, batch_size=3):
batches = []
for i in range(0, len(data), batch_size):
batch = data[i:i+batch_size]
batches.append(batch)
return batches
raw_data = [1, 2, 3, 4, 5, 6, 7, 8, 9]
processed_batches = process_data_batches(raw_data)
print("Data Batches:", processed_batches)
Advanced Filtering Techniques
3. Conditional List Manipulation
def filter_by_condition(data):
## Extract elements meeting specific criteria
filtered_data = [x for x in data if x % 2 == 0]
return filtered_data
numbers = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
even_numbers = filter_by_condition(numbers)
print("Even Numbers:", even_numbers)
4. List Manipulation with Slicing
def rotate_list(lst, k):
## Rotate list by k positions
k = k % len(lst)
return lst[-k:] + lst[:-k]
original_list = [1, 2, 3, 4, 5]
rotated_list = rotate_list(original_list, 2)
print("Rotated List:", rotated_list)
Technique |
Complexity |
Use Case |
Simple Slicing |
O(1) |
Basic data extraction |
Batch Processing |
O(n) |
Large dataset handling |
Conditional Filtering |
O(n) |
Selective data processing |
Slicing Workflow
graph TD
A[Input Data] --> B[Slice Selection]
B --> C{Condition Check}
C --> |Yes| D[Process Data]
C --> |No| E[Skip/Filter]
D --> F[Output Result]
Real-world Application Example
def analyze_student_scores(scores, top_n=3):
## Sort and extract top performing students
sorted_scores = sorted(scores, reverse=True)
top_performers = sorted_scores[:top_n]
return top_performers
class_scores = [85, 92, 78, 95, 88, 76, 90]
top_students = analyze_student_scores(class_scores)
print("Top 3 Performers:", top_students)
Error Handling and Edge Cases
def safe_slice_extraction(data, start, end):
try:
return data[start:end]
except IndexError:
print("Invalid slice range")
return []
sample_data = [10, 20, 30, 40, 50]
result = safe_slice_extraction(sample_data, 2, 10)
LabEx recommends practicing these practical slicing techniques to enhance your Python data manipulation skills.