Difference Between range() and xrange() in Python:

These two functions are used for iterating for a certain number of times in for loops. In Python 3 for data science, it does not contain xrange(). In Python 2 range() behaves similar to xrange().

  • range() – It returns the list of numbers that are created using range() function.
  • xrange() – Use for returning the generator object which is use for display of numbers by looping. A particular range is displayed only on demand, and so, it is known as “Lazy evaluation”.

Below we will be comparing both the range() and xrange() functions on some parameters.

The parameters are as follows:

Return Type:

  • In the case of range() the return type is list.
  • In case of xrange() an xrange() object is returned.

python for data science

Memory:

The range created by range() which is stored in a variable takes up much more memory than xrange(). This happens because the return type of range() is list and that o xrange() is object.

Operations usage:

We have seen that range() returns a list so, whatever operation is possible on a list is possible in case of range(). But in the case of xrange() it is not possible as it returns xrange object.

Speed:

xrange() is faster when compared to range() as it uses lazy evaluation which is already discussed at the beginning of this article.

Note:

  • When writing codes that should run on both Python 3 and Python 2 range() is the only option.
  • range() will be faster in case we are iterating on the same sequence multiple times.
  • In terms of memory range() is the worst one can get.

If you want to learn more about range in python for data science then you can check this and this.

Leave a Reply

Your email address will not be published. Required fields are marked *

This site uses Akismet to reduce spam. Learn how your comment data is processed.