How does the Python's range function work?
How does Python’s range() function actually work behind the scenes?
What does it return, and how does it generate sequences efficiently without storing every number in memory?
Python’s range() function is used to generate a sequence of numbers — typically for loops, iterations, and indexing tasks. What’s interesting is that range() doesn’t actually create a full list of numbers in memory. Instead, it produces a lazy sequence (an immutable and efficient range object) that generates values on demand.
Basic Usage
range() can take 1, 2, or 3 arguments:
- range(stop) → numbers from 0 to stop - 1
- range(start, stop) → numbers from start to stop - 1
- range(start, stop, step) → numbers with increments/decrements based on step
Example:
for i in range(2, 10, 2):
print(i)
Output: 2 4 6 8 Key Features
It does not store all numbers at once — memory efficient
You can convert it to a list if needed:
list(range(5)) # [0, 1, 2, 3, 4]It supports negative steps, allowing reverse loops
It is an immutable sequence type
Why is range() efficient?
It calculates each value only when needed, not ahead of time
Works great for large ranges, for example:
range(1_000_000_000) This won’t crash your system because the numbers aren’t all stored
In simple words, range() is a smart way for Python to generate sequences efficiently, making loops faster and memory usage much lower compared to actual lists.