Fix - NameError: name 'xrange' is not defined in Python

avatar

Borislav Hadzhiev

Wed Apr 20 20222 min read

banner

Photo by Raychan

Fix - NameError: name 'xrange' is not defined in Python #

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.

nameerror name xrange is not defined

Here is an example of how the error occurs.

main.py
# ⛔️ 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.

main.py
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:

NameDescription
startAn integer representing the start of the range (defaults to 0)
stopGo up to, but not including the provided integer
stepRange 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.

main.py
for n in range(5): print(n) result = list(range(5)) # 👇️ [0, 1, 2, 3, 4] print(result)
The example shows that if the 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.

main.py
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.

main.py
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.

main.py
result = list(range(1, 0)) # 👇️ [] print(result)
Use the search field on my Home Page to filter through my more than 1,000 articles.