Python官方文檔里是這樣說的:
xrange([start,] stop[, step])This function is very similar to range(), but returns an ``xrange object'' 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 xrange() over range() is minimal (since xrange() 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 break).Note: xrange() 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.
range可以返回一個可以用於所有目的的普通列表對象,而xrange將返回一個特殊目的的對象,尤其適用於迭代操作,但是xrange並不返回一個迭代器,如果需要這樣一個迭代器,可以調用iter(xrange(x))。xrange返回的特殊目的對象比range返回的列表對象消耗較少的內存(范圍比較大的時候)。但是對特殊目的對象執行循環操作的開銷略微高於對列表執行循環的開銷。
>>> print range(5) [0, 1, 2, 3, 4] >>> print xrange(5) xrange(5)
其中,range將返回一個普通列表,但是xrange將返回一個特殊目的對象,將顯示為其自身的特殊方式。