The built-in function range() is used to return a sequence of integer numbers by specifying starting and ending points in the sequence. This resultant sequence is immutable means values cannot be changed. For repeating a task a specific number of times we can use this range() method with loops.
range(stop)
range(start, stop[, step]) #where stop is an integer indicates stop position.
Takes three parameters. If the start index is not given it starts from 0, and it will increment the value by 1 continue until the stop index.
Parameter | Description | Required / Optional |
---|---|---|
start | An integer number specifying at which position to start. Default is 0 | optional |
stop | An integer number specifying at which position to stop | Required |
step | An integer determines the increment between each integer in the sequence | optional |
The result sequence is starting from 0 to stop - 1.if the stop is negative or 0 it returns an empty sequence.
r[n] = start + step*n (for both positive and negative step)
where, n >=0 and r[n] < stop (positive step)
where, n >= 0 and r[n] > stop (negative step)
If the step is zero it raises a ValueError exception. If non zero it returns a sequence according to the formula. If it doesn't meet the value constraint, an empty sequence is returned.
Input | Return Value |
---|---|
integer | integer sequence |
# empty range
print(list(range(0)))
# using range(stop)
print(list(range(10)))
# using range(start, stop)
print(list(range(1, 10)))
Output:
[] [0, 1, 2, 3, 4, 5, 6, 7, 8, 9] [1, 2, 3, 4, 5, 6, 7, 8, 9]
start = 2
stop = 14
step = 2
print(list(range(start, stop, step)))
Output:
[2, 4, 6, 8, 10, 12]
start = 2
stop = -14
step = -2
print(list(range(start, stop, step)))
# value constraint not met
print(list(range(start, 14, step)))
Output:
[2, 0, -2, -4, -6, -8, -10, -12] []