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

后端 未结 28 2087
深忆病人
深忆病人 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 04:14

    In python 2.x

    range(x) returns a list, that is created in memory with x elements.

    >>> a = range(5)
    >>> a
    [0, 1, 2, 3, 4]
    

    xrange(x) returns an xrange object which is a generator obj which generates the numbers on demand. they are computed during for-loop(Lazy Evaluation).

    For looping, this is slightly faster than range() and more memory efficient.

    >>> b = xrange(5)
    >>> b
    xrange(5)
    

提交回复
热议问题