Help on built-in function range in Module __builtin__:range (...) Range (stop), list of integers range (start, stop[, Step)), List of integers Return A list containing an A Rithmetic progression of integers. Range (I, j) returns [I, I+1, i+2, ..., j-1]; Start (!) defaults to 0. When step is given, it specifies the increment (or decrement). For example, range (4) returns [0, 1, 2, 3]. The end point is omitted! These is exactly the valid indices for a list of 4 elements. (END)
The above is a description of the range function, with three parameters representing the start, end position, and step size, respectively.
Here's how to use it:
In [2]: Range (Ten) out[2]: [0, 1, 2, 3, 4, 5, 6, 7, 8, 9]in [3]: Range (1,) out[3]: [1, 2, 3, 4, 5, 6, 7, 8, 9]in [4]: Rang E (1, 2) out[4]: [1, 3, 5, 7, 9]in [5]: Type (range (1, 3)) out[5]: Listin [6]: For I in range: ...: print I
...: 0123456789
The xrange () is described below:
Help on Class xrange in module __builtin__:class xrange (object) | Xrange (stop), Xrange object | Xrange (Start, stop[, Step), Xrange object | | Like range (), but instead of returning a list, returns an Object | Generates the numbers in the range on demand. For looping, this is | Slightly faster than range () and more memory efficient. | | Methods defined here: | | __getattribute__ (...) | x.__getattribute__ (' name ') <==> X.name | | __getitem__ (...) | x.__getitem__ (y) <==> x[y] | | __iter__ (...) | X.__ITER__ () <==> iter (x) | | __len__ (...) | x.__len__ () <==> len (x) | | __reduce__ (...) | | __repr__ (...) | x.__repr__ () <==> repr (x) | | __reversed__ (...) | Returns a reverse iterator. | | ---------------------------------------------------------------------- | Data and other attributes defined here: | | __new__ = <built-in method __new__ of type object> | t.__new__ (S),...) A new object with type S, a subtype of T (END)
The difference between the two is that Xrange returns an object that can be iterated, and the range returns a list. At the same time more efficient and faster.
The reason is that when the implementation of the use of yield (hmm, the source did not see, the specific comparison can look at http://ju.outofmemory.cn/entry/122781),
Therefore, more memory is saved, the larger the difference is more obvious.
About the definition of an iterative object see: https://eastlakeside.gitbooks.io/interpy-zh/content/Generators/Iterable.html
That is, whenever you define a __iter__ method that can return an iterator, or __getitem__, it is an iterative object.
Xrange use the following methods:
in [+]: List (xrange (3)) out[13]: [0, 1, 2]in []: A = xrange (3) in []: a.__iter__out[15]: <method-wrapper ' __iter__ ' of Xrange object at 0x7f415be1bdc8>in [+]: a.__iter__ () out[16]: <rangeiterator at 0x7f415aa27210>
The difference between Python range () and xrange ()