List Comprehension with range() in Python

Data Science Tool Box Mar 18, 2026

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() or pd.date_range() for large numeric or date sequences in data science
  • Use descriptive variable names (e.g., i for index, idx for 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

Related Tutorials

Share:
Last updated: March 2026
Built-in Functions in Python 2026 str() in Python 2026: String Conversion + Modern Formatting & Best Practices memoryview with JAX in Python 2026: Zero-Copy NumPy → JAX Array Interop + Efficient ML Examples memoryview with TensorFlow in Python 2026: Zero-Copy NumPy → Tensor Interop + GPU Pinning & ML Examples memoryview with TensorFlow in Python 2026: Zero-Copy NumPy → Tensor Interop + ML Examples memoryview with NumPy & PyTorch in Python 2026: Zero-Copy Views, Efficient Slicing & ML Interop Examples memoryview with NumPy in Python 2026: Zero-Copy Views, Efficient Slicing & Real ML Examples memoryview() in Python 2026: Zero-Copy Magic for Large Binary Data + Real Examples import() in Python 2026: How It Works, Security Risks & Modern Alternatives (importlib) zip() in Python 2026: How to Use It, strict=True Behavior & Real-World Examples vars() in Python 2026: Accessing Object Namespace + Modern Introspection Patterns type() in Python 2026: Dynamic Type Inspection & Object Creation + Modern Patterns tuple() in Python 2026: Immutable Sequences + Modern Patterns & Best Practices super() in Python 2026: Method Resolution & Modern Inheritance Patterns sum() in Python 2026: Summing Iterables + Modern Numeric Patterns & Best Practices staticmethod() in Python 2026: Static Methods, Utility Functions & Modern Best Practices sorted() in Python 2026: Sorting Iterables + Modern Patterns & Best Practices slice() in Python 2026: Creating Slice Objects + Modern Patterns & Best Practices setattr() in Python 2026: Dynamic Attribute Setting + Modern Patterns & Safety set() in Python 2026: Mutable Sets Creation + Modern Patterns & Best Practices