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

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

    xrange only stores the range params and generates the numbers on demand. However the C implementation of Python currently restricts its args to C longs:

    xrange(2**32-1, 2**32+1)  # When long is 32 bits, OverflowError: Python int too large to convert to C long
    range(2**32-1, 2**32+1)   # OK --> [4294967295L, 4294967296L]
    

    Note that in Python 3.0 there is only range and it behaves like the 2.x xrange but without the limitations on minimum and maximum end points.

提交回复
热议问题