The range()
function in Python is a built-in function that generates a sequence of numbers. For example,
# creates a sequence of numbers from 0 to 4
numbers = range(5)
for number in numbers:
print(number)
Output
0 1 2 3 4
Note: range()
is a useful function that is commonly used in a for
loop to iterate the loop a certain number of times.
By the way, the range()
function returns an immutable sequence of numbers that can be easily converted to lists, tuples etc.
# creates a sequence of numbers from 0 to 4
numbers = range(5)
# converting to list and printing it
print(list(numbers)) # [0, 1, 2, 3, 4]
range() Syntax
The range()
function can take a maximum of three arguments:
range(start, stop, step)
The start
and step
arguments in the range()
function are optional.
Example 1: range() with One Argument
If we pass a single argument to range()
, it returns a sequence of arguments starting from 0 up to that number (excluding the number).
# numbers from 0 to 3 (4 is not included)
numbers = range(4)
print(list(numbers)) # [0, 1, 2, 3]
Note: If we pass a single argument to range()
, it means we are passing the stop argument.
Example 2: range() with Two Arguments
If we pass two arguments to range()
, it returns a sequence of numbers starting the first argument (inclusive) to the last argument (exclusive).
# numbers from 2 to 3 (4 is not included)
numbers = range(2, 4)
print(list(numbers)) # [2, 3]
# numbers from -2 to 2 (3 is not included)
numbers = range(-2, 3)
print(list(numbers)) # [-2, -1, 0, 1, 2]
Note: If we pass two arguments to range()
, it means we are passing the start argument and the stop argument.
Example 3: range() with Three Arguments
If we pass three arguments, this means
start
is the first argumentstop
is the second argumentstep
is the third argument
The step
argument specifies the gap between two numbers in the sequence. Let's see an example of this:
# numbers from 10 to 20 with 3 increments between numbers
numbers = range(10, 20, 3)
print(list(numbers))
Output
[10, 13, 16, 19]
The range(10, 20, 3)
function generates a sequence of numbers starting from 10, incrementing by 3 each time, and stopping before it reaches 20.
The range()
function stops before it reaches the ending value specified, in this case 20, the sequence stops at 19.