Explain Codes LogoExplain Codes Logo

Nameerror: Global name 'xrange' is not defined in Python 3

python
python-3
python-2
best-practices
Alex KataevbyAlex Kataev·Jan 13, 2025
TLDR

xrange was discontinued in Python 3. Your go-to solution is range, which now behaves like Python 2's xrange, generating numbers without reserving memory space for the entire list, like a well-behaved guest not hogging all the cake 🍰!

# Channel your inner Python 3 spirit! for i in range(5): print(i)

Simply replace xrange with range and your code will live happily ever after in Python 3.

Breaking Down the Changes

Transitioning a codebase from Python 2 to Python 3 involves more than waving a magic wand and yelling "Accio xrange!".

While replacing xrange with range solves this issue, other Python 2 behaviors need modifications.

A neat trick while upgrading is to alias xrange to range:

try: # if Python 2 range = xrange except NameError: # if Python 3 pass

This ensures your code can dine with Python 2 and 3 without causing a scene.

Avoiding Potential Pitfalls

While celebrating your victory over xrange, don't forget other possible culprits:

  • Print statements now require parentheses, just like hugs 🤗!
  • Division behavior changed to true division, no half-hearted attempts here!
  • Unicodes handle strings differently, not all languages handle tantrums well.
  • Many standard library changes, like a renovated library with a new layout.

The Transition Marathon

Transitioning is more than a sprint of changing xrange to range. It’s a marathon that may include:

String type handling

Python 3 differentiated text (str) from binary data (bytes), this may cause encoding and decoding errors if not handled.

New dictionary methods

Methods like .keys(), .values(), or .items() return "views", not lists. Just wrap them with a list constructor like handling a present 🎁:

keys_list = list(my_dict.keys())

Error handling

Multiple except clauses now require parenthesized tuples, they love group hugs:

try: # code block except (ExceptionType1, ExceptionType2) as e: # handle exceptions

Syntax changes

A few more differences in Python 2 and Python 3 include list comprehensions, integer division operations, and unpacking arguments.