Skip to content

range()

The range() function returns a sequence of numbers, starting from 0 by default, and increments by 1 (by default), and stops before a specified number.

Usage

Syntax 1:

range(x)
  • x is a number, and it start from 0 and end with (x - 1)
  • ex: range(5), the data returning will be [0, 1, 2, 3, 4].

Syntax 2:

range(x, y)
  • x is a starting number, y is a ending number (where y is not included in the end)
  • start from x and end with (y - 1)
  • ex: range(5, 10), the data returning will be [5, 6, 7, 8, 9].

Syntax 3:

range(x, y, step)
  • x is a starting number, y is a ending number (where y is not included in the end), z is the step
  • start from x and end with (y - 1)
  • the increments will follow the value of step (default: 1).
  • ex: range(5, 10, 2), the data returning will be [5, 7, 9].

Example

range.py

py
print("Range 1")
range1 = range(5)
for i in range1:
    print(i)

print("Range 2") 
range2 = range(5, 10)
for i in range2:
    print(i)

print("Range 3") 
range3 = range(5, 10, 2)
for i in range3:
    print(i)

Results:

Range 1
0
1
2
3
4
Range 2
5
6
7
8
9
Range 3
5
7
9