Mastering the Python Range() Function Guide
Loops are the backbone of programming, and `range()` is the backbone of Python loops. Learn how to control your iterations precisely.
What is Python Range?
Unlike languages like C or Java that use `for(int i=0; i<10; i++)`, Python simplifies iteration using the range type. It generates a sequence of immutable numbers.
It creates a lazy sequence, meaning it doesn't store all the numbers in memory at once; it generates them one by one as your loop asks for them. This makes it incredibly memory efficient.
The Syntax Variants
There are three ways to call this function:
2. range(start, stop)
3. range(start, stop, step)
1. Loop "N" Times (range(stop))
If you provide just one argument, Python assumes you start at 0 and increment by 1.
for i in range(5):
print(i)
# Output: 0, 1, 2, 3, 4
# Notice: It STOPS before 5. It does not include 5.
2. Start From a Specific Number (range(start, stop))
If you don't want to start at 0, specify the start index.
for i in range(2, 6):
print(i)
# Output: 2, 3, 4, 5
3. Skip Numbers (range(start, stop, step))
The third argument is the "step" (increment).
for i in range(0, 10, 2):
print(i)
# Output: 0, 2, 4, 6, 8
Common Tasks & Tricks
Looping Backwards (Negative Step)
To count down, use a negative step value. Crucial: Your start must be larger than your stop.
for i in range(5, 0, -1):
print(i)
# Output: 5, 4, 3, 2, 1
Creating a List of Numbers
Since `range` is lazy, printing it directly just shows `range(0, 5)`. To see the numbers, convert it to a list.
numbers = list(range(5))
print(numbers)
# Output: [0, 1, 2, 3, 4]
Iterating Over a List with Index
Sometimes you need both the index and the value. Combine `range` with `len`, or better yet, use `enumerate`.
fruits = ["apple", "banana", "cherry"]
# The Basics (Classic Way)
for i in range(len(fruits)):
print(f"Index {i} is {fruits[i]}")
# The "Pythonic" Way (Recommended)
for i, fruit in enumerate(fruits):
print(f"Index {i} is {fruit}")
FAQ: Common Pitfalls
Q: Why does range(1, 5) not include 5?
A: Python uses 0-based indexing logic. This is consistent with slicing lists. `my_list[0:5]`
also excludes index 5. It ensures that `range(0, n)` produces exactly `n` items.
Q: Can I use floats? range(0.5, 5.5)?
A: No. `range` only accepts integers. For floating point ranges (e.g., 0.5, 1.0, 1.5), used
`numpy.arange` or `numpy.linspace`.