引自 python官方文档
- range ( stop ) range ( start, stop [, step ] )
-
This is a versatile function to create lists containing arithmetic progressions. It is most often used in loops. The arguments must be plain integers. If the step argument is omitted, it defaults to 1. If the start argument is omitted, it defaults to 0. The full form returns a list of plain integers [start, start + step, start + 2 * step, ...]. If step is positive, the last element is the largeststart + i * step less than stop; if step is negative, the last element is the smallest start + i * step greater than stop. step must not be zero (or else is raised). Example:
>>> range(10)[0, 1, 2, 3, 4, 5, 6, 7, 8, 9]>>> range(1, 11)[1, 2, 3, 4, 5, 6, 7, 8, 9, 10]>>> range(0, 30, 5)[0, 5, 10, 15, 20, 25]>>> range(0, 10, 3)[0, 3, 6, 9]>>> range(0, -10, -1)[0, -1, -2, -3, -4, -5, -6, -7, -8, -9]>>> range(0)[]>>> range(1, 0)[]
- xrange ( stop ) xrange ( start, stop [, step ] )
-
This function is very similar to , but returns an instead of a list. This is an opaque sequence type which yields the same values as the corresponding list, without actually storing them all simultaneously. The advantage of over is minimal (since still has to create the values when asked for them) except when a very large range is used on a memory-starved machine or when all of the range’s elements are never used (such as when the loop is usually terminated with). For more information on xrange objects, see and .
CPython implementation detail: is intended to be simple and fast. Implementations may impose restrictions to achieve this. The C implementation of Python restricts all arguments to native C longs (“short” Python integers), and also requires that the number of elements fit in a native C long. If a larger range is needed, an alternate version can be crafted using the module: islice(count(start, step), (stop-start+step-1+2*(step<0))//step).
- 官方文档中说明range返回的是一个list,而xrange返回的是一个xrange对象,并且xrange更加简洁快速,所以在程序当中应当尽量使用xrange。
-