Understanding Python's range() Function: Syntax, Parameters, and Examples
This article explains Python's range() function, detailing its return type differences between Python 2 and 3, syntax variations, parameter meanings, and provides multiple code examples illustrating usage with various start, stop, and step values, as well as converting the result to lists or tuples.
Python's range() function returns an iterable object in Python 3 (not a list), while in Python 2 it returns a list directly; converting the Python‑3 iterable to a list can be done with list(range(...)) .
Supported syntaxes are range(stop) and range(start, stop[, step]) .
Parameters:
start : the starting value (default 0).
stop : the end value (exclusive).
step : the increment (default 1).
Basic usage example:
>> range(5)
range(0, 5)Iterating over the range:
for i in range(5):
print(i)Output:
0
1
2
3
4Converting to a list or tuple:
list(range(5)) # [0, 1, 2, 3, 4]
tuple(range(5)) # (0, 1, 2, 3, 4)Examples with start, stop, and step:
list(range(0, 30, 5)) # [0, 5, 10, 15, 20, 25]
list(range(0, 10, 2)) # [0, 2, 4, 6, 8]
list(range(0, -10, -1)) # [0, -1, -2, -3, -4, -5, -6, -7, -8, -9]Extended note: In Python 3, range() replaces Python 2's xrange() . Generating a list or tuple from a range works the same way in both versions, but Python 2 creates the full list immediately, whereas Python 3 creates elements lazily during iteration.
Test Development Learning Exchange
Test Development Learning Exchange
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.