In this post, I gonna show you - with some very simply examples - how the python built-in function range works!
Let's start with the official official python help:
>>>help(range)
Help on built-in function range in module __builtin__:
range(...)
range([start,] stop[, step]) -> list of integers
Return a list containing an arithmetic 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 are exactly the valid indices for a list of 4 elements.
Basically the list of integers is built with the following simple rules:
1) The list starts with start, an optional parameter having 0 as its default value
3) The step of the elements is given by step, an optional parameter having 1 as its default value
2) The last element is ALWAYS smaller than stop!
If N indicates the overall number of elements in the list, each element a_i is calculated according to the rule:
a_i = start + step*(i-1)
and the last element MUST be smaller than stop:
a_N = start + step *(N-1) < stop
as a consequence...
N <1+ (stop-start)/step
The result of 1+(stop-start)/step can be an interger or decimal number doesn't matter. The important thing is that N is integer and smaller than 1+(start - start)/step!
Understood? Let's see the examples!
1) What is the output for range(1,9,2)?
start=1
stop=9
step=2
N<1+(stop-start)/step =1 + (9-1)/2=5 hence N=4! Indeed...
>>>>range(1,9,2)
[1, 3, 5, 7]
2) What is the output for range(1,8,2)?
start=1
stop=8
step=2
N < 1+(stop-start)/step =1 + (8-1)/2=4.5 hence N=4! Indeed...
>>>>range(1,8,2)
[1, 3, 5, 7]
3) What is the output for range(9)?
start=0 [default]
stop=9
step=1 [default]
N < 1+(stop-start)/step =1 + (9-1)/1=9 hence N=8! Indeed...
>>>>range(9)
[0, 1, 2, 3, 4, 5, 6, 7, 8]
4) What is the output for range(9,3,-2)?
start=9
stop=3
step=-2
N < 1+(stop-start)/step =1 + (3-9)/(-2)=4 hence N=3! Indeed...
>>>>range(9,3,-2)
[9, 7, 5, 4]
NOTE:
N represents the TOTAL number of elements but python labels them starting from 0 and ending at (N-1)!
No comments:
Post a Comment
Your comment will be visible after approval.