Control Flow
Range Function
Generating sequences with range()
Interview: Fundamental for loops and algorithm problems — tests understanding of lazy sequences
The range() function generates immutable sequences of integers. In Python 3, it returns a range object (not a list), which generates values on demand — making it extremely memory-efficient even for billions of elements.
Three Forms of range()
range(stop): Generates 0, 1, 2, ..., stop-1. Example:range(5)→ 0,1,2,3,4range(start, stop): Generates start, start+1, ..., stop-1. Example:range(2, 7)→ 2,3,4,5,6range(start, stop, step): Generates start, start+step, start+2*step, ... Example:range(0, 10, 2)→ 0,2,4,6,8- Negative step: Counts down:
range(5, 0, -1)→ 5,4,3,2,1. Note: stop value is exclusive - Empty range:
range(0)orrange(5, 0)(start > stop with positive step) produces no values
Range Object Properties
- Lazy evaluation:
range(10**9)uses the same memory asrange(10)— it computes values on demand - Supports len():
len(range(0, 10, 2))→ 5 (computed in O(1)) - Supports indexing:
range(10)[3]→ 3,range(10)[-1]→ 9 - Supports 'in' operator:
5 in range(10)→ True (O(1) check, not iteration) - Immutable: Cannot modify elements after creation
- Hashable: Can be used as dictionary keys (unlike lists)
Performance Insight
In Python 2, range() created a full list in memory. Python 3's range is a sequence object with O(1) memory. For Python 2 compatibility code, use xrange() instead of range().
Common Patterns
- Repeat N times:
for _ in range(n):— use underscore when index isn't needed - Index-based access:
for i in range(len(lst)):— but preferenumerate()instead - Slicing with range:
list(range(10))[::2]→ [0, 2, 4, 6, 8] - Creating lists:
list(range(5))→ [0, 1, 2, 3, 4]
Common Pitfall
range() only accepts integers. Using floats raises TypeError. For float ranges, use numpy.arange() or a list comprehension: [i * 0.1 for i in range(10)].
Use Cases
Looping a specific number of times (repeat N times)
Generating index sequences for list/array traversal
Creating evenly-spaced integer sequences
Memory-efficient large-range iteration in algorithms
Common Mistakes
Using range(len(lst)) instead of enumerate() when you need both index and value
Forgetting that the stop value is exclusive (range(5) gives 0-4, not 0-5)
Trying to use floats with range() — it only accepts integers
Using range() in Python 2 thinking it is lazy — use xrange() instead