Python range() Function

The range() function in Python generates a sequence of numbers. By default, the sequence starts at 0, increments by 1, and stops before the specified number.

Example

# create a sequence from 0 to 3 (4 is not included)
numbers = range(4)

# iterating through the sequence
for i in numbers:
    print(i)

Output

0
1
2
3

range() Syntax

The syntax of range() is:

range(start, stop, step)

The start and step arguments are optional.


range() Return Value

The range() function returns an immutable sequence of numbers.


Example 1: range(stop)

# create a sequence from 0 to 3 (4 is not included)
numbers = range(4)

# convert to list and print it
print(list(numbers))    # Output: [0, 1, 2, 3]

In this example, we have converted the range sequence to a list.


Example 2: range(start, stop)

# create a sequence from 2 to 4 (5 is not included)
numbers = range(2, 5)
print(list(numbers))    # [2, 3, 4]

# create a sequence from -2 to 3
numbers = range(-2, 4)    
print(list(numbers))    # [-2, -1, 0, 1, 2, 3]

# creates an empty sequence
numbers = range(4, 2) 
print(list(numbers))    # []

Example 3: range(start, stop, step)

# create a sequence from 2 to 10 with increment of 3
numbers = range(2, 10, 3)
print(list(numbers))    # [2, 5, 8]

# create a sequence from 4 to -1 with increment of -1
numbers = range(4, -1, -1)    
print(list(numbers))    # [4, 3, 2, 1, 0]

# range(0, 5, 1) is equivalent to range(5)
numbers = range(0, 5, 1) 
print(list(numbers))    # [0, 1, 2, 3, 4]

range() in for Loop

The range() function is commonly used in for loop to iterate the loop a certain number of times. For example,

# iterate the loop five times
for i in range(5):
    print(f'{i} Hello')
0 Hello
1 Hello
2 Hello
3 Hello
4 Hello

Video: Python range() Function

Did you find this article helpful?