Should you always favor xrange() over range()?

后端 未结 12 2175
后悔当初
后悔当初 2020-11-22 13:36

Why or why not?

12条回答
  •  夕颜
    夕颜 (楼主)
    2020-11-22 14:15

    A good example given in book: Practical Python By Magnus Lie Hetland

    >>> zip(range(5), xrange(100000000))
    [(0, 0), (1, 1), (2, 2), (3, 3), (4, 4)]
    

    I wouldn’t recommend using range instead of xrange in the preceding example—although only the first five numbers are needed, range calculates all the numbers, and that may take a lot of time. With xrange, this isn’t a problem because it calculates only those numbers needed.

    Yes I read @Brian's answer: In python 3, range() is a generator anyway and xrange() does not exist.

提交回复
热议问题