Python detailed differences in the range and xrange

Use a .range

 Function Description: range ([start,] stop [, step]), according to the step and the start and stop specified range setting step of generating a sequence.

>>> range(5) 
[0, 1, 2, 3, 4] 
>>> range(1,5) 
[1, 2, 3, 4] 
>>> range(0,6,2)
[0, 2, 4]

Two .xrange usage

Function Description: usage and range are identical, the difference is not generated in an array, but 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]

Can be known from the above example: the sequence of numbers to be generated when large, with many advantages will xrange performance than the range, since no one up to open up a lot of memory space, which are basically two cycles when to use:

for i in range(0, 100):
    print(i)
for i in xrange(0, 100):
    print(i)

Both the output is the same, but in fact there are many different, range will directly generate a list objects; and xrange does not generate a list directly, but each call which returns a value of:

So xrange cycle performance better than the range, especially when the return is worth a lot, try to use xrange, unless you return a list.

Reprinted: https://blog.csdn.net/ikerpeng/article/details/44809573?utm_source=blogxgwz2

Guess you like

Origin www.cnblogs.com/sggggr/p/12197561.html