range() vs xrange() in Python:

 range() vs xrange() in Python:

  • The range() and xrange() are two functions that could be used to iterate a certain number of times in for loops in Python. 
  • In Python 3, there is no xrange , but the range function behaves like xrange in Python 2.
  • If you want to write code that will run on both Python 2 and Python 3, you should use range().

    • range() – This returns a range object (a type of iterable).
    • xrange() – This function returns the generator object that can be used to display numbers only by looping. The only particular range is displayed on demand and hence called "lazy evaluation".

  • The points of comparison are: 
    • Return Type:
      • range() returns – range object. 
      • xrange() returns – xrange() object.
      • Example:
        • a=range(5)
          print(type(a)) # O/P: 
          <type 'list'>
        • x=xrange(6)
          print(type(x)) #O/P: 
          <type 'xrange'>
    • Operation Usage:
      • range() returns the list, all the operations that can be applied on the list can be used on it.
      • xrange() returns the xrange object, operations associated to list cannot be applied on them
      • Example:
        • a=range(1,5)
          print(a[2:3]) 
          # O/P: [3]
        • a=xrange(1,5)
          print(a[2:3]) # O/P: 
          TypeError: sequence index must be integer, not 'slice'
    • Memory:
      • The variable storing the range created by range() takes more memory as compared to the variable storing the range using xrange().
        The basic reason for this is the return type of range() is list and xrange() is xrange() object.
                 import sys
                    a = range(1,10)
                    x = xrange(1,10)
                    print (sys.getsizeof(a)) #144
                    print (sys.getsizeof(x)) #40
    • Speed:
      • Because of the fact that xrange() evaluates only the generator object containing only the values that are required by lazy evaluation, therefore is faster in implementation than range().

Thanks for reading!!

Comments

Popular posts from this blog

Python namespaces & LEGB rule in Python