Deep Dive into Python’s range Function: Syntax, Usage, and Performance
This article explains Python's built‑in range function, covering its lazy generation, memory efficiency, syntax variations, practical examples, common pitfalls, and advanced techniques such as reverse iteration and enumeration.
Python’s range is a powerful built‑in function that creates immutable numeric sequences on demand, enabling lazy generation and low memory consumption compared to materializing a full list.
Basic Syntax
The function can be called as range(stop) or range(start, stop[, step]). start defaults to 0, stop is required and exclusive, and step defaults to 1.
Typical Usages
Only stop value – prints numbers 0‑9:
for i in range(10):
print(i, end=" ") # 0 1 2 3 4 5 6 7 8 9Start and stop – prints 5‑9:
for i in range(5, 10):
print(i, end=" ") # 5 6 7 8 9Custom step – prints 1,3,5,7,9:
for i in range(1, 10, 2):
print(i, end=" ") # 1 3 5 7 9Reverse order – using a negative step:
for i in range(10, 1, -2):
print(i, end=" ") # 10 8 6 4 2Conversion to List
Although range itself is immutable, it can be materialized with list():
r = range(5)
print(list(r)) # [0, 1, 2, 3, 4]Key Advantages
Because numbers are generated lazily, range uses very little memory even for large spans. For example:
r = range(10**6)
print(len(r)) # 1000000, memory footprint is tinyThe iteration speed is also higher than building a list first.
Common Scenarios
Iterating a simple loop:
for i in range(3):
print(f"Processing item {i}")Generating a list of numbers:
numbers = list(range(1, 11)) # [1, 2, ..., 10]Index‑based iteration over another sequence:
data = ["a", "b", "c"]
for i in range(len(data)):
print(f"Index {i}, Value {data[i]}")Important Caveats
The stop value is exclusive (e.g., range(5) yields 0‑4).
A step of zero raises ValueError (e.g., range(1,10,0)).
Python automatically supports arbitrarily large integers, so ranges beyond typical 32‑bit limits still work.
Advanced Techniques
Membership test using in:
r = range(10)
print(5 in r) # True
print(15 in r) # FalseReverse iteration with reversed():
for i in reversed(range(5)):
print(i, end=" ") # 4 3 2 1 0Combining with enumerate():
data = ["apple", "banana", "cherry"]
for i, value in enumerate(data):
print(f"Index {i}: {value}")Real‑World Examples
Pagination logic:
page_size = 10
total_items = 35
for start in range(0, total_items, page_size):
end = min(start + page_size, total_items)
print(f"Processing items {start} to {end-1}")Generating an arithmetic progression:
start = 1
end = 20
step = 3
arithmetic_sequence = list(range(start, end, step))
print(arithmetic_sequence) # [1, 4, 7, 10, 13, 16, 19]Summary
rangeoffers three flexible parameters ( start, stop, step) to control sequence bounds and step size, generates numbers lazily for efficient memory use, supports iteration, conversion to other collections, membership testing, reverse traversal, and integrates smoothly with enumerate and pagination patterns.
Signed-in readers can open the original source through BestHub's protected redirect.
This article has been distilled and summarized from source material, then republished for learning and reference. If you believe it infringes your rights, please contactand we will review it promptly.
How this landed with the community
Was this worth your time?
0 Comments
Thoughtful readers leave field notes, pushback, and hard-won operational detail here.
