0 votes
in Python by
What is the difference between range and xrange functions in Python 2.X?

1 Answer

0 votes
by

The range() and xrange() functions are built-in functions in Python programming that are used to iterate over a sequence of values. Both the range() and xrange() functions are used with the for() loops to iterate over certain number of times. Both the range() and xrange() functions create a list of the specified range of values. So, if we provide (1, 10) as the parameter to both the functions then it will create a list in the memory having 9 elements (1 to 10 excluding the 10th number).

The range() and xrange() functions are used in Python3 and Python2 respectively. As we know Python3 does not support backward compatibility, so the xrange() function (which was used in Python2) cannot be used in Python3 but the range() function can be used with Python2. Now, if we want our code to work on both the Python2 and Python3 interpreters then we should use the range() function.

Now, the difference between range and xrange in Python lies in their working speed and return values. The range() function is comparatively faster than the xrange() function. The range() function supports list slicing on the other hand, the xrange() function does not support list slicing. The range() function return a range a of iterable type objects on the other hand the xrange() function return the generator object.

Note:

  • The range() function of Python-3 is basically a re-implementation of the xrange() function of Python2.
  • List slicing is a way to get the subsets of any list or an array.
  • Generator object is basically an iterator object having a sequence of values.

Related questions

0 votes
asked May 17, 2020 in Python by sharadyadav1986
0 votes
asked Jan 3 in Python by DavidAnderson
...