Home  >  Article  >  Backend Development  >  Should python prefer xrange over range?

Should python prefer xrange over range?

silencement
silencementOriginal
2019-05-25 14:43:182701browse

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

Should python prefer xrange over range?

xrange

##Function usage:

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.

Example

Should python prefer xrange over range?

As can be seen from the above example: the range() and xrange() methods are exactly the same, and they are basically used during loops , and the output results of both are the same. The biggest difference between the two is that range() will directly generate a list object; xrange() generates an xrange object instead of a list object, and each call returns the value.

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!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn