0 votes
in Python Pandas by
range ()  vs and xrange () functions in Python?

1 Answer

0 votes
by

In Python 2 we have the following two functions to produce a list of numbers within a given range.

range()

xrange()

 

in Python 3, xrange() is deprecated, i.e. xrange() is removed from python 3.x.

Now In Python 3, we have only one function to produce the numbers within a given range i.e. range() function.

 

But, range() function of python 3 works same as xrange() of python 2 (i.e. internal implementation of range() function of python 3 is same as xrange() of Python 2).

So The difference between range() and xrange() functions becomes relevant only when you are using python 2.

range() and xrange() function values

a). range() creates a list i.e., range returns a Python list object, for example, range (1,500,1) will create a python list of 499 integers in memory. Remember, range() generates all numbers at once.

b).xrange() functions returns an xrange object that evaluates lazily. That means xrange only stores the range arguments and generates the numbers on demand. It doesn’t generate all numbers at once like range(). Furthermore, this object only supports indexing, iteration, and the len() function.

On the other hand xrange() generates the numbers on demand. That means it produces number one by one as for loop moves to the next number. In every iteration of for loop, it generates the next number and assigns it to the iterator variable of for loop.

Printing return type of range() function:

range_numbers = range(2,10,2)

 

print (“The return type of range() is : “)

print (type(range_numbers ))

 

Output:

 

The return type of range() is :

<type ‘list’>

 

Printing return type of xrange() function:

 

xrange_numbers = xrange(1,10,1)

 

print “The return type of xrange() is : ”

print type(xrange_numbers )

 

Output:

 

The return type of xrange() is :

<type ‘xrange’>

Related questions

0 votes
asked May 17, 2020 in Python by sharadyadav1986
0 votes
asked Aug 13, 2021 in Python Pandas by SakshiSharma
...