top button
Flag Notify
    Connect to us
      Site Registration

Site Registration

What is the difference between Xrange and range in Python?

+2 votes
474 views
What is the difference between Xrange and range in Python?
posted Dec 3, 2014 by Kali Mishra

Share this question
Facebook Share Button Twitter Share Button LinkedIn Share Button

1 Answer

+2 votes

For performance, especially when you're iterating over a large range, xrange() is usually better. However, there are still a few cases why you might prefer range():

In python 3, range() does what xrange() used to do and xrange() does not exist. If you want to write code that will run on both Python 2 and Python 3, you can't use xrange().

range() can actually be faster in some cases - eg. if iterating over the same sequence multiple times. xrange() has to reconstruct the integer object every time, but range() will have real integer objects. (It will always perform worse in terms of memory however)

xrange() isn't usable in all cases where a real list is needed. For instance, it doesn't support slices, or any list methods.

There are a couple of posts mentioning how range() will be upgraded by the 2 to3 tool. For the record, here's the output of running the tool on some sample usages of range() and xrange()

answer Dec 3, 2014 by Amit Kumar Pandey
...