Difference between xrange and range in python

I encountered xrange and range today, and deliberately checked the difference between the two: Same point: (same usage) The range function is range([start,] stop[, step]), which is set according to the range specified by start and stop and step. The fixed step xrange function is xrange([start,] stop[, step]), according to the difference between the range specified by start and stop and the step set by step: range generates a sequence, and the list object xrange is a generator range The function is range([start,] stop[, step]), which generates a sequence according to the range specified by start and stop and the step size set by step. For example: >>> range(5) [0, 1, 2, 3, 4] >>> range(1,5) [1, 2, 3, 4] >>> range(0,6,2) [ 0, 2, 4] The usage of xrange is exactly the same as that of range, the difference is that instead of a list object, it produces a generator. >>> xrange(5) xrange(5) >>> list(xrange(5)) [0, 1, 2, 3, 4] >>> xrange(1,5) xrange(1, 5) >>> list(xrange(1,5)) [1, 2, 3, 4] >>> xrange(0,6,2) xrange(0, 6, 2) >>> list(xrange(0,6,2) ) [0, 2, 4] It can be known from the above example: when you want to generate a large sequence of numbers, using xrange will perform much better than range, because it does not need to open up a large memory space. Both xrange and range are basically used when looping. for i in range(0, 10): print i for i in xrange(0, 10):

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=325561196&siteId=291194637