Practical Indexing Examples
Real-World Indexing Scenarios
1. Data Processing with Lists
## Processing temperature data
temperatures = [22.5, 23.1, 19.8, 25.3, 20.6, 21.9]
## Extract morning temperatures
morning_temps = temperatures[:3]
print("Morning Temperatures:", morning_temps)
## Calculate average afternoon temperature
afternoon_temps = temperatures[3:]
avg_afternoon_temp = sum(afternoon_temps) / len(afternoon_temps)
print("Average Afternoon Temperature:", avg_afternoon_temp)
2. String Manipulation
## Email validation and extraction
email = "[email protected]"
## Extract username
username = email.split('@')[0]
print("Username:", username)
## Domain extraction
domain = email.split('@')[1]
print("Domain:", domain)
Complex Indexing Techniques
## Advanced list processing
numbers = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
## Extract even numbers
even_numbers = numbers[1::2]
print("Even Numbers:", even_numbers)
## Reverse and filter
filtered_reversed = numbers[::-2]
print("Reversed Every Second Number:", filtered_reversed)
Data Structure Navigation
graph TD
A[Indexing Strategies] --> B[List Navigation]
A --> C[Dictionary Access]
A --> D[Nested Structure Indexing]
Nested Dictionary Indexing
## Complex nested dictionary
students = {
'class_a': {
'john': {'age': 20, 'grades': [85, 90, 88]},
'sarah': {'age': 22, 'grades': [92, 95, 91]}
},
'class_b': {
'mike': {'age': 21, 'grades': [78, 82, 80]}
}
}
## Access specific nested information
john_first_grade = students['class_a']['john']['grades'][0]
print("John's First Grade:", john_first_grade)
Indexing Method |
Time Complexity |
Best Use Case |
Simple Indexing |
O(1) |
Direct element access |
Slicing |
O(k) |
Extracting range |
Negative Indexing |
O(1) |
Accessing from end |
Safe Indexing Techniques
def safe_index(collection, index, default=None):
try:
return collection[index]
except (IndexError, KeyError):
return default
## Example usage
sample_list = [10, 20, 30]
result = safe_index(sample_list, 5, "Not Found")
print(result) ## Prints "Not Found"
Advanced Use Cases
## Transform data using indexing
raw_data = [
['Alice', 25, 'Engineer'],
['Bob', 30, 'Manager'],
['Charlie', 22, 'Designer']
]
## Extract names
names = [person[0] for person in raw_data]
print("Names:", names)
## Filter by age
young_professionals = [person for person in raw_data if person[1] < 28]
print("Young Professionals:", young_professionals)
With LabEx, you can explore these practical indexing examples through interactive coding environments that provide immediate feedback and hands-on learning experiences.