range(stop)
range(start, stop[, step])
The range function represents an immutable sequence of integers. If used by passing it a single stop argument, it generates a sequence of consecutive integers between 0 and stop -1. If used by passing it two arguments, start and stop, it generates a sequence of consecutive integers between start and stop -1. In the latter case, the inclusion of a third step argument forces the sequence of numbers to be generated with a "step" jump between one number and the next.
The step argument cannot be zero.
If step is positive, start must be a number less than stop. In any other case, the generated sequence will be empty.
If step is negative, start must be a number greater than stop. Also in this case, if not, an empty sequence will be generated.
One of the advantages of range with respect to other similar structures (such as a list or a tuple) is that range will always occupy a minimum amount of memory (the amount necessary to store the start, stop and step arguments), calculating the generated numbers or subranges when necessary.
- start: First number to generate in the sequence.
- stop: Limit value of the sequence to be generated.
- step: (Optional) value to add to each number to generate the next one.
start, stop, and step must be whole numbers.
The range function generates an object of type range that represents a sequence of integers.
We can generate a range of numbers with the range function and use it in a for loop:
for i in range(4):
print(i)
0
1
2
3
In this case we have only passed one argument to the function (number 4), so the generated sequence is made up of the integers between 0 and 3, both included.
If we pass two arguments to the function, for example 3 and 7, we would be generating a sequence of 4 numbers, between 3 and 6 both included:
for i in range(3, 7):
print(i)
3
4
5
6
A third argument represents the jump between the numbers to be generated. In this example we generate the range and convert it to a list with the list function:
list(range(5, 30, 6))
[5, 11, 17, 23, 29]
In this case, the first value is 5 and the next are calculated by adding the increment (6) to the previous one.
It is possible to extract a selection from the generated sequence as if it were a list or tuple:
r = range(10, 20)
r
range(10, 20)
r [3: 6]
range(13, 16)
If the step parameter takes a negative value, the numbers are generated by subtracting that value from the previous number:
list(range(10, 5, -1))
[10, 9, 8, 7, 6]