English | 简体中文 | 繁體中文 | Русский язык | Français | Español | Português | Deutsch | 日本語 | 한국어 | Italiano | بالعربية

Python Basic Tutorial

Python Flow Control

Python Functions

Python Data Types

Python File Operations

Python Objects and Classes

Python Date and Time

Advanced Python Knowledge

Python Reference Manual

Python range() Usage and Example

Python built-in functions

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() parameters

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 value

The range() function returns an immutable numerical sequence object, depending on the definition used:

range(stop)

  • Returns from0tostop-1A numerical sequence of

  • IfstopIsNegative numbers or 0,Then it returns an empty sequence.

range(start, stop[, step])

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

Example1:How does range work in Python?

# 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]

Example2:Use range() to create an even number list between given numbers

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]

Example3:How to use range() with negative step?

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]
[]

Python built-in functions