Practical Range Examples
Data Processing Scenarios
List Comprehension with Range
## Generate squared numbers
squares = [x**2 for x in range(10)]
print(squares) ## [0, 1, 4, 9, 16, 25, 36, 49, 64, 81]
Iteration Techniques
Reverse Iteration
## Counting down
for i in range(10, 0, -1):
print(i) ## 10, 9, 8, 7, 6, 5, 4, 3, 2, 1
Mathematical Operations
Prime Number Detection
def is_prime(n):
if n < 2:
return False
for i in range(2, int(n**0.5) + 1):
if n % i == 0:
return False
return True
primes = [num for num in range(2, 50) if is_prime(num)]
print(primes)
Range Workflow Visualization
graph TD
A[Range Function] --> B[Input Parameters]
B --> C[Start Value]
B --> D[Stop Value]
B --> E[Step Value]
A --> F[Sequence Generation]
Common Use Case Patterns
Scenario |
Range Application |
Example |
Indexing |
List/Array Access |
items[range(0, len(items), 2)] |
Sampling |
Periodic Selection |
range(0, total_items, sampling_rate) |
Batching |
Data Processing |
range(0, data_length, batch_size) |
Advanced Range Manipulations
Multi-Dimensional Iteration
## Nested range iteration
for x in range(3):
for y in range(3):
print(f"Coordinate: ({x}, {y})")
## Efficient range-based filtering
def filter_large_dataset(data):
return [item for i, item in enumerate(data) if i % 2 == 0]
LabEx Pro Tip
Always consider memory efficiency and computational complexity when using range in large-scale data processing scenarios.