How to Solve Python NameError: name ‘xrange’ is not defined

by | Programming, Python, Tips

The built-in xrange() method in Python 2 does not exist in Python 3. In Python 3, we can use the function range() to produce a range of numbers. If you try to use xrange() in a Python 3 program, you will raise the NameError: name ‘xrange’ is not defined.

To solve this error, use the range() function instead of xrange() on Python 3.

This tutorial will go through the error in detail and how to solve it with code examples.


NameError: name ‘xrange’ is not defined

The NameError exception occurs when the object we want to call is not initialized in the current scope of the Python program. The xrange() function was replaced by range(). The syntax of range() is as follows:

range(start, stop, step)

Parameters

  • start: Optional. An integer number specifying which position to start from. Default is 0.
  • stop: Required. An integer number specifying which position to stop (not included).
  • step: Optional. An integer number specifying the increment. Default is 1.

The range function returns an object, whereas the xrange() function generates a list of numbers.

Example

Let’s look at an example where we want to calculate the square of each number from 2 to a specified number. Let’s look at the code:

import sys

# Check Python version

print(sys.version)

end_point = int(input("Enter the number to calculate squares up to: "))

for i in xrange(2, end_point):
    print(f'{i} squared = {i**2}')

Let’s run the code to see what happens:

3.8.8 (default, Apr 13 2021, 12:59:45) 
[Clang 10.0.0 ]
Enter the number to calculate squares up to: 10
---------------------------------------------------------------------------
NameError                                 Traceback (most recent call last)
<ipython-input-2-b0efe34caea9> in <module>
      7 end_point = int(input("Enter the number to calculate squares up to: "))
      8 
----> 9 for i in xrange(2, end_point):
     10     print(f'{i} squared = {i**2}')
     11 

NameError: name 'xrange' is not defined

We get the NameError because we are using Python 3. We can only use the xrange() function in Python 2

Solution #1: Use range()

We can use the range() function instead of xrange() to solve this error. Let’s look at the revised code:

import sys

# Check Python version

print(sys.version)

end_point = int(input("Enter the number to calculate squares up to: "))

# Replace xrange with range

for i in range(2, end_point):

    print(f'{i} squared = {i**2}')

Let’s run the code to see the result:

3.8.8 (default, Apr 13 2021, 12:59:45) 
[Clang 10.0.0 ]
Enter the number to calculate squares up to: 10
2 squared = 4
3 squared = 9
4 squared = 16
5 squared = 25
6 squared = 36
7 squared = 49
8 squared = 64
9 squared = 81

The last number to calculate the square of is 9 because the range() function is not inclusive of the stop parameter.

Solution #2: Change Python Major Version from 3 to 2

If you want to use an earlier Python major version, you can use Conda to create a virtual environment with a Python 2 interpreter. To create a virtual environment, use the following command:

conda create -n py27 python=2.7

Then activate the environment using:

conda activate py27

You should see “py27” next to the command line prompt in parenthesis.

Let’s check what Python version we are using the sys module

import sys
print(sys.version)
2.7.16 |Anaconda, Inc.| (default, Sep 24 2019, 16:55:38) 
[GCC 4.2.1 Compatible Clang 4.0.1 (tags/RELEASE_401/final)]

Then, we can use the xrange() function. Note that we also have to change the print statements not to include parentheses. We use parentheses for print statements in Python 3.

end_point = int(input("Enter the number to calculate squares up to: "))

for i in xrange(2, end_point):

    print i, 'squared =', i**2

Let’s run the code to get the output:

Enter the number to calculate squares up to: 10
2 squared = 4
3 squared = 9
4 squared = 16
5 squared = 25
6 squared = 36
7 squared = 49
8 squared = 64
9 squared = 81

Generally, you want to avoid using Python 2 as this version is no longer supported, which means any Python 2 library or method you use may have bugs or security issues. It would be best to choose the range() solution in Python 3.

Summary

Congratulations on reading to the end of this tutorial! The NameError: name ‘xrange’ is not defined occurs when you try to call the xrange() method using Python major version 3. You can only use xrange() in Python 2.

To solve this error, use the range() method when using Python 3. Otherwise, revert to Python 2 by creating a virtual environment.

For further reading on deprecated functions in Python 2, go to the articles:

To learn more about Python for data science and machine learning, go to the online courses page on Python for the most comprehensive courses available.

Have fun and happy researching!

Profile Picture
Senior Advisor, Data Science | [email protected] | + posts

Suf is a senior advisor in data science with deep expertise in Natural Language Processing, Complex Networks, and Anomaly Detection. Formerly a postdoctoral research fellow, he applied advanced physics techniques to tackle real-world, data-heavy industry challenges. Before that, he was a particle physicist at the ATLAS Experiment of the Large Hadron Collider. Now, he’s focused on bringing more fun and curiosity to the world of science and research online.

Buy Me a Coffee ✨