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

后端 未结 28 2426
深忆病人
深忆病人 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条回答
  •  萌比男神i
    2020-11-22 04:15

    range(): range(1, 10) returns a list from 1 to 10 numbers & hold whole list in memory.

    xrange(): Like range(), but instead of returning a list, returns an object that generates the numbers in the range on demand. For looping, this is lightly faster than range() and more memory efficient. xrange() object like an iterator and generates the numbers on demand.(Lazy Evaluation)

    In [1]: range(1,10)
    
    Out[1]: [1, 2, 3, 4, 5, 6, 7, 8, 9]
    
    In [2]: xrange(10)
    
    Out[2]: xrange(10)
    
    In [3]: print xrange.__doc__
    
    xrange([start,] stop[, step]) -> xrange object
    

提交回复
热议问题