NameError: global name 'xrange' is not defined in Python 3


I am getting an error when running a python program:

Traceback (most recent call last):
  File "C:Program Files (x86)Wing IDE 101", line 110, in <module>
  File "C:Program Files (x86)Wing IDE 101", line 27, in __init__
  File "C:Program Files (x86)Wing IDE 101", line 17, in __init__
builtins.NameError: global name 'xrange' is not defined

The game is from here.

What causes this error?

Asked By: Pip



You are trying to run a Python 2 codebase with Python 3. xrange() was renamed to range() in Python 3.

Run the game with Python 2 instead. Don’t try to port it unless you know what you are doing, most likely there will be more problems beyond xrange() vs. range().

For the record, what you are seeing is not a syntax error but a runtime exception instead.

If you do know what your are doing and are actively making a Python 2 codebase compatible with Python 3, you can bridge the code by adding the global name to your module as an alias for range. (Take into account that you may have to update any existing range() use in the Python 2 codebase with list(range(...)) to ensure you still get a list object in Python 3):

    # Python 2
except NameError:
    # Python 3, xrange is now named range
    xrange = range

# Python 2 code that uses xrange(...) unchanged, and any
# range(...) replaced with list(range(...))

or replace all uses of xrange(...) with range(...) in the codebase and then use a different shim to make the Python 3 syntax compatible with Python 2:

    # Python 2 forward compatibility
    range = xrange
except NameError:

# Python 2 code transformed from range(...) -> list(range(...)) and
# xrange(...) -> range(...).

The latter is preferable for codebases that want to aim to be Python 3 compatible only in the long run, it is easier to then just use Python 3 syntax whenever possible.

Answered By: Martijn Pieters

I agree with the last answer.But there is another way to solve this problem.You can download the package named future,such as pip install future.And in your .py file input this “from past.builtins import xrange”.This method is for the situation that there are many xranges in your file.

Answered By: Not Genius

add xrange=range in your code 🙂 It works to me.

Answered By: Frost Xu


Python 2 xrange to

Python 3 range

Rest all same.

Answered By: Hari_pb

I solved the issue by adding this import
More info

from past.builtins import xrange
Answered By: Andrés Gutiérrez

in python 2.x, xrange is used to return a generator while range is used to return a list. In python 3.x , xrange has been removed and range returns a generator just like xrange in python 2.x. Therefore, in python 3.x you need to use range rather than xrange.

Answered By: Ahmad Farhan