當(dāng)我們?cè)谘h(huán)中用到for或者while針對(duì)一段數(shù)字進(jìn)行循環(huán)的時(shí)候,我們其實(shí)是可以直接表達(dá)其范圍的,但是為啥python還是要引入range函數(shù)呢?
作為python的內(nèi)置函數(shù),個(gè)人推測(cè)range是在其他內(nèi)置函數(shù)中需要用到list的index時(shí)候需要的,所以可以看到range函數(shù)的定義:
Return an object that produces a sequence of integers from start (inclusive) to stop (exclusive) by step. range(i, j) produces i, i+1, i+2, …, j-1. start defaults to 0, and stop is omitted! range(4) produces 0, 1, 2, 3. These are exactly the valid indices for a list of 4 elements. When a step is given, it specifies the increment (or decrement).
包含開(kāi)始數(shù)字,而將停止的數(shù)字排除在外,比如range(5):

有意思的是,這是python3的range函數(shù),而python2的xrange函數(shù)反而是更加高速和占用較小內(nèi)存的。
可以利用python的內(nèi)嵌函數(shù)timeit 與 sys.getsizeof 進(jìn)行測(cè)試:
python -m timeit 'for i in range(1000000):' ' pass'
10 loops, best of 3: 90.5 msec per loop
# testing xrange()
python -m timeit 'for i in xrange(1000000):' ' pass'
10 loops, best of 3: 51.1 msec per loop
--------------------------------------------
xr = xrange(1, 10000)
r = range(1, 10000)
size_xr = sys.getsizeof(xr)
size_r = sys.getsizeof(r)
print(f"The xrange() function uses {size_xr} bytes of memory.")
print(f"The range() function uses {size_r} bytes of memory.")
輸出是:
The xrange() function uses 24 bytes of memory.
The xrange() function uses 80064 of memory.