Name xrange Is Not Defined Error in Python

Name xrange Is Not Defined Error in Python

This tutorial will explore resolving the error name 'xrange' is not defined in Python.

Resolve the name 'xrange' is not defined Error in Python

Let us try to understand why this particular error occurs. Let us first start by trying to replicate this issue.

We can do this with the help of the following block of code.

for i in xrange(5):
	print("I love python")

Note: It is important to install Python 3.0.0 or later on your device to replicate this error.

The code above results in the error below on your console.

line 1: name xrange is not defined

The main cause for this problem is that you have installed Python version 3.0.0 or later. The keyword xrange does not work in any Python versions that occur after 2.9.0.

There are two ways to solve this problem.

  1. Downgrading your Python version.

    We can do this with the help of the following command.

    conda install python=2.9.0
    
    Note

Please run the command above on a conda environment only.

  1. The second method involves discarding the keyword xrange and replacing it with range. It does the same job that xrange used to do in the earlier versions.

    This can be understood better with the help of the following block of code.

    for i in range(5):
    	print("I love Python")
    

The output of the code above can be illustrated as follows.

I love Python
I love Python
I love Python
I love Python
I love Python

As we can see, the error has been resolved.

Thus, with the two techniques above, we can successfully resolve the error name 'xrange' is not defined in Python versions 3.0.0 or later.

Preet Sanghavi avatar Preet Sanghavi avatar

Preet writes his thoughts about programming in a simplified manner to help others learn better. With thorough research, his articles offer descriptive and easy to understand solutions.

LinkedIn GitHub

Related Article - Python Error

  • Python PermissionError: [WinError 5] Access Is Denied
  • Python TypeError: 'DataFrame' Object Is Not Callable
  • Python TypeError: Can't Convert 'List' Object to STR
  • Local Variable Referenced Before Assignment Error in Python
  • Python Handling Socket.Error: [Errno 104] Connection Reset by Peer
  • Python Is Not Recognized in Windows 10