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

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

    On a requirement for scanning/printing of 0-N items , range and xrange works as follows.

    range() - creates a new list in the memory and takes the whole 0 to N items(totally N+1) and prints them. xrange() - creates a iterator instance that scans through the items and keeps only the current encountered item into the memory , hence utilising same amount of memory all the time.

    In case the required element is somewhat at the beginning of the list only then it saves a good amount of time and memory.

提交回复
热议问题