Home > Article > Backend Development > Should python prefer xrange over range?
Comparison between range and xrange
range
Function usage:
range( stop)
range(start,stop[,step])
Function description:
This is a general function that creates a list containing a sequence. It is most commonly used in for loops. Parameters must be ordinary integers. If the step parameter is omitted, it defaults to 1. If the start parameter is omitted, it defaults to 0. The complete form of this function returns a list of integers [start, start step, start 2 * step, …]. If step is positive, then the last element start i * step is the largest and smaller than stop; if step is negative, then the last element start i * step is the smallest and larger than stop. step must not be zero (otherwise a ValueError will be raised).
Example
xrange
xrange(stop)
xrange(start,stop[,step])
Function description:
This function is very similar to range(), but it returns the xrange object type instead of a list. This is a lazy sequence type that generates the same values as the corresponding list, but does not actually store them together at the same time. xrange() has little advantage over range() (since xrange() still has to create the required values) unless you are using a very large range on a memory-constrained machine or all elements of the range are never used (e.g. when the loop is often terminated by break).
xrange object type description
The xrange type is an immutable sequence, usually used for loops. The benefit of the xrange type is that an xrange object always occupies the same amount of memory, regardless of the size of the range it represents. But it doesn't have consistent performance benefits.
xRange objects have very little behavior: they only support indexing, iteration, and the len() function.
The above is the detailed content of Should python prefer xrange over range?. For more information, please follow other related articles on the PHP Chinese website!