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

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

    range(x,y) returns a list of each number in between x and y if you use a for loop, then range is slower. In fact, range has a bigger Index range. range(x.y) will print out a list of all the numbers in between x and y

    xrange(x,y) returns xrange(x,y) but if you used a for loop, then xrange is faster. xrange has a smaller Index range. xrange will not only print out xrange(x,y) but it will still keep all the numbers that are in it.

    [In] range(1,10)
    [Out] [1, 2, 3, 4, 5, 6, 7, 8, 9]
    [In] xrange(1,10)
    [Out] xrange(1,10)
    

    If you use a for loop, then it would work

    [In] for i in range(1,10):
            print i
    [Out] 1
          2
          3
          4
          5
          6
          7
          8
          9
    [In] for i in xrange(1,10):
             print i
    [Out] 1
          2
          3
          4
          5
          6
          7
          8
          9
    

    There isn't much difference when using loops, though there is a difference when just printing it!

提交回复
热议问题