range is a built-in type that represents an immutable, lazy sequence of integers. range(stop) generates integers from 0 to stop - 1; range(start, stop) generates from start to stop - 1; and range(start, stop, step) generates with a given stride. range does not create a list — it computes each value on demand, using constant memory regardless of the range size.
range is the standard tool for index-based iteration in Python: for i in range(10): loops from 0 to 9. However, Pythonic code often avoids explicit indexing in favour of iterating directly over collections (for item in items:) or using enumerate() when both the index and value are needed (for i, item in enumerate(items):).
range objects support membership testing (5 in range(10) is O(1), not O(n), because range can compute the answer arithmetically), len(), indexing (range(10)[3]), and slicing (range(10)[2:5]). They are commonly converted to lists (list(range(10))) when a materialised sequence is needed. The fact that range is lazy — producing values on demand rather than storing them — makes it efficient even for very large ranges: range(10**18) uses the same memory as range(10).
Discussed in:
- Chapter 4: Control Flow — The range() Function
Also defined in: Textbook of Medical Statistics