Python xrange vs range

Difference between xrange() and range() in python

The main difference is that range() returns Python list object and xrange() returns a xrange() sequence object. range() creates a static list at run-time unlike xrange(). xrange() uses yielding technique to generate values as needed.

If you do range(1, 100) it will create a list in memory of 99 elements.

Is Xrange faster than range?

Xrange() performs better in the terms of memory. However, xrange() reconstructs the integer object every time, but range() will always have a real integer object and therefore range() is faster if iterating over the same sequence multiple times, on the other hand xrange() evaluates lazily.

Note: In python 3.x, range() do the same what xrange() used to do and xrange() does not exist in Python 3. Also range() returns a range object in python python 3.

import xrange() in Python 3

As xrange() is deprecated in python 3, you cannot import it. If you want a Python program that can run on both python 2 and python 3 then use range() function instead of xrange().

Python xrange not defined error If you try to import xrange in python 3 using PyCharm, you will get a name error or unresolved reference error like the one given below:

builtins.NameError: global name 'xrange' is not defined

How range() works in Python 2 and Python 3?

range() works very different in subsequent version of Python 2 and Python 3. In Python 2, the range() function returns a list of numbers:

>>> range(5)
[0, 1, 2, 3, 4]
On the other hand xrange() class represented an iterable object which we can use in the same manner to loop over, but it was lazy:

>>> xrange(5)
xrange(5)
Now the kicker comes here you will be really amazed to know that to remove the laziness of xrange() they removed original range() function and renamed xrange() to range() in Python 3.

>>> range(5)
range(0, 5)

range() Python 3 vs Python 2

In Python 3, range() does not return the list but instead it returns a range object. But don't worry if you want the Python 2 behavior for range() in Python 3, you need to convert the range object to a list.

>>> list(range(5))
[0, 1, 2, 3, 4]

Python range() function

Syntax : range(start, stop, step) Example :
x = range(5)
for numb in x:
	print(num)

''' Output of above code:- 

python range_demo.py

0
1
2
3
4

'''

Does range start at 0?

The range() is 0-index based. It means that the list starts at index 0. The range(lower_limit, upprt_limit) creates interger upto upper_limit but will not include the upper_limit.

For example, range(0,3) generates integers staring from 0 to 2 i.e. 0, 1, 2 (3 integers generated).

Python xrange() function

Syntax : xrange (stop) xrange (start, stop[, step]) Example :
for i in xrange(10):
	print i

''' Output of above code:- 

python xrange_demo.py

0
1
2
3
4
5
6
7
8
9

'''
Have you noticed that Syntax of range() and xrange()? They are both same because in Python 3 range() is equivalent to xrange(), it does the job of xrange().