List Comprehension with range() in Python
Combining range() with list comprehensions is a very common and powerful pattern in data science. It allows you to generate sequences of numbers, create index-based operations, or build test datasets quickly and cleanly.
TL;DR — Common Patterns
[expression for i in range(n)]– Generate sequences[f(i) for i in range(start, stop, step)]– With custom range- Very useful for creating dummy data, indices, or repeating patterns
1. Basic Usage
# Simple sequence
squares = [i ** 2 for i in range(10)]
print(squares)
# With start, stop, and step
even_numbers = [i for i in range(0, 21, 2)]
print(even_numbers)
2. Real-World Data Science Examples
import pandas as pd
import numpy as np
# Example 1: Create a list of feature names with indices
feature_names = [f"feature_{i:03d}" for i in range(50)]
# Example 2: Generate dummy data for testing
dummy_data = [
{"id": i, "value": round(np.random.normal(100, 15), 2), "category": "A" if i % 3 == 0 else "B"}
for i in range(1000)
]
df = pd.DataFrame(dummy_data)
# Example 3: Create lagged feature indices
lags = [f"lag_{i}" for i in range(1, 8)] # lag_1 to lag_7
print(lags)
3. Advanced Pattern – Nested range with Conditions
# Create a grid of combinations
grid = [(x, y) for x in range(5) for y in range(5) if x != y]
# Generate month-year strings for time series analysis
months = [f"{year}-{month:02d}" for year in range(2023, 2027) for month in range(1, 13)]
print(months[:10])
4. Best Practices in 2026
- Use
range()inside list comprehensions when you need numeric sequences or indices - Keep comprehensions readable — avoid deeply nested range expressions
- Prefer
np.arange()orpd.date_range()for large numeric or date sequences in data science - Use descriptive variable names (e.g.,
ifor index,idxfor position) - Combine with
enumerate()when you need both the generated value and its position
range() Inside Comprehensions
range(start, stop, step) produces evenly spaced integers without building a list, and comprehensions turn those numbers into whatever you need: labels, offsets, test data or index positions.
Like slices, range excludes the stop value. A negative step counts down. Because range is lazy and supports len() and indexing, it is very memory-friendly even for large sequences.
Nested ranges in a comprehension create grids of combinations, which is handy for parameter searches or small lookup tables.
Worked Example: Labels, Steps and Grids
We create month labels, sample positions and a parameter grid with range.
months = [f"2026-{m:02d}" for m in range(1, 13)]
print(months[:3], len(months))
every_fifth = [i for i in range(0, 50, 5)]
print(every_fifth)
countdown = [i for i in range(5, 0, -1)]
print(countdown)
grid = [(depth, rate) for depth in range(2, 5) for rate in (0.1, 0.3)]
print(len(grid), grid[:3])
range(1, 13) gives the twelve months because 13 is excluded. The grid comprehension creates six combinations of depth and rate, ready to loop over in a simple parameter search.
Practical Tips
Remember that range objects can be stored and reused, unlike generators.
Comprehensions over range are also an easy way to create small test inputs. A list such as [i % 7 for i in range(50)] has repeated values and a known pattern, so you can check the output of a function by hand before running it on real data.
When the numbers themselves are the goal, prefer list(range(...)) to an identity comprehension like [i for i in range(...)]; it is shorter and says exactly what it does. For floating-point steps, use NumPy's arange or linspace, because range accepts only integers.
Common Mistakes
- Forgetting that stop is excluded.
- Using range(len(seq)) where enumerate is clearer.
- Expecting range to accept float steps.
- Creating huge nested grids by accident.
Quick Summary
- range(start, stop, step) excludes stop.
- Negative steps count down.
- range is lazy and memory-friendly.
- Nested ranges build parameter grids.
Conclusion
List comprehensions combined with range() provide a clean and efficient way to generate sequences and perform index-based operations in data science. In 2026, this pattern is commonly used for creating dummy datasets, generating feature names, building time series indices, and many other repetitive tasks. Use it when the logic is simple and clear.
Next steps:
- Practice using list comprehensions with
range()to generate indices, dummy data, or feature lists in your next project