Borislav Hadzhiev
Wed Apr 20 2022·2 min read
Photo by Raychan
The Python "NameError: name 'xrange' is not defined" when we use the
xrange()
function in a Python 3 codebase. To solve the error, use the
range()
function instead, because xrange
was renamed to range
in
Python 3.
Here is an example of how the error occurs.
# ⛔️ NameError: name 'xrange' is not defined. Did you mean: 'range'? for n in xrange(1, 10): print(n)
To solve the error, simply replace xrange
with range
.
for n in range(1, 10): print(n)
The xrange
function was renamed to range
in Python 3.
The range class is
commonly used for looping a specific number of times in for
loops and takes
the following parameters:
Name | Description |
---|---|
start | An integer representing the start of the range (defaults to 0 ) |
stop | Go up to, but not including the provided integer |
step | Range will consist of every N numbers from start to stop (defaults to 1 ) |
If you only pass a single argument to the range()
constructor, it is
considered to be the value for the stop
parameter.
for n in range(5): print(n) result = list(range(5)) # 👇️ [0, 1, 2, 3, 4] print(result)
start
argument is omitted, it defaults to 0
and if the step
argument is omitted, it defaults to 1
.If values for the start
and stop
parameters are provided, the start
value
is inclusive, whereas the stop
value is exclusive.
result = list(range(1, 5)) # 👇️ [1, 2, 3, 4] print(result)
Notice that the range goes up to, but not including 5
because the stop
value
is exclusive.
If you need to create a range that consists of every N numbers, provide a value
for the step
parameter.
result = list(range(1, 7, 2)) # 👇️ [1, 3, 5] print(result)
We passed a value of 2
for the step
parameter. Notice that the start
value
is still inclusive, and the stop
value is still exclusive.
If the value for the stop
parameter is lower than the value for the start
parameter, the range will be empty.
result = list(range(1, 0)) # 👇️ [] print(result)