English | 简体中文 | 繁體中文 | Русский язык | Français | Español | Português | Deutsch | 日本語 | 한국어 | Italiano | بالعربية
The range() type returns an immutable numerical sequence between the given starting and ending integers.
The range() constructor has two definition forms:
range(stop) range(start, stop[, step])
range() mainly uses three parameters with the same usage in both definitions:
start -An integer, starting from which the integer sequence is returned
stop-To return the integer in the integer sequence to be returned.
Integer range in1AEnds at the endpoint.
step (optional) -An integer value that determines the increment between each integer in the sequence
The range() function returns an immutable numerical sequence object, depending on the definition used:
Returns from0tostop-1A numerical sequence of
IfstopIsNegative numbers or 0,Then it returns an empty sequence.
The return value is calculated according to the following formula under the given constraints:
r[n] = start + step*n (for both positive and negative step) where, n >=0 and r[n] < stop (for positive step) where, n >= 0 and r[n] > stop (for negative step)
(ifstep)step defaults to1.Returns fromstarttostop-1The ending number sequence.
(ifstep is zero)TriggerValueErrorException
(if step is not zero)CheckValue constraintWhether it meets the constraint and returns the sequence according to the formula.
If the value constraint is not met, then returnEmpty Sequence。
# Empty range print(list(range(0))) # Use range(stop) print(list(range(10)) # Use range(start, stop) print(list(range(1, 10))
When running the program, the output is:
[] [0, 1, 2, 3, 4, 5, 6, 7, 8, 9] [1, 2, 3, 4, 5, 6, 7, 8, 9]
Note:We have converted the range toPython list,because range() returns an object similar to a generator, which prints output on demand.
However, the range object returned by the range constructor can also be accessed by its index. It supports both positive and negative indices.
You can access the range object by index as follows:
rangeObject[index]
start = 2 stop = 14 step = 2 print(list(range(start, stop, step)))
When running the program, the output is:
[2, 4, 6, 8, 10, 12]
start = 2 stop = -14 step = -2 print(list(range(start, stop, step))) # Does not meet value constraints print(list(range(start, 14, step)))
When running the program, the output is:
[2, 0, -2, -4, -6, -8, -10, -12] []