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

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

    What?
    range returns a static list at runtime.
    xrange returns an object (which acts like a generator, although it's certainly not one) from which values are generated as and when required.

    When to use which?

    • Use xrange if you want to generate a list for a gigantic range, say 1 billion, especially when you have a "memory sensitive system" like a cell phone.
    • Use range if you want to iterate over the list several times.

    PS: Python 3.x's range function == Python 2.x's xrange function.

提交回复
热议问题