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

后端 未结 28 2434
深忆病人
深忆病人 2020-11-22 03:14

Apparently xrange is faster but I have no idea why it\'s faster (and no proof besides the anecdotal so far that it is faster) or what besides that is different about

28条回答
  •  梦如初夏
    2020-11-22 03:57

    range() in Python 2.x

    This function is essentially the old range() function that was available in Python 2.x and returns an instance of a list object that contains the elements in the specified range.

    However, this implementation is too inefficient when it comes to initialise a list with a range of numbers. For example, for i in range(1000000) would be a very expensive command to execute, both in terms of memory and time usage as it requires the storage of this list into the memory.


    range() in Python 3.x and xrange() in Python 2.x

    Python 3.x introduced a newer implementation of range() (while the newer implementation was already available in Python 2.x through the xrange() function).

    The range() exploits a strategy known as lazy evaluation. Instead of creating a huge list of elements in range, the newer implementation introduces the class range, a lightweight object that represents the required elements in the given range, without storing them explicitly in memory (this might sound like generators but the concept of lazy evaluation is different).


    As an example, consider the following:

    # Python 2.x
    >>> a = range(10)
    >>> type(a)
    
    >>> b = xrange(10)
    >>> type(b)
    
    

    and

    # Python 3.x
    >>> a = range(10)
    >>> type(a)
    
    

提交回复
热议问题