What is the range() function in Python? (12/100 Days of Python)
The range()
function is a built-in function in Python that returns a sequence of numbers, starting from 0 by default, increments by 1 (also by default), and ends at a specified number. It's commonly used in loops to repeat an action a certain number of times (we’ll cover loops in the next tutorial).
A few basic examples of the range function include:
print(list(range(5))) # [0, 1, 2, 3, 4]
print(list(range(2, 5))) # [2, 3, 4]
print(list(range(1, 8))) # [1, 2, 3, 4, 5, 6, 7]
print(list(range(5, 3))) # []
The range function accepts a parameter indicating where it should stop (excluding the indicated number). It can be customized to start from a different than 0. Besides, it can also be customized to increment by a different number. By default, the range()
function increments the values by 1, but it can be changed to increment those by 2, 3, or even a negative number like -1.
range(end) # Start from 0, increment by 1, end at `end`
range(start, end) # Start from `start`, increment by 1, end at `end`
range(start, end, step) # Start from `start`, increment by `step`, end at `end`
# Examples
print(list(range(2, 15, 4))) # [2, 6, 10, 14]
print(list(range(11, 2, -1))) # [11, 10, 9, 8, 7, 6, 5, 4, 3]
print(list(range(-5, 5))) # [-5, -4, -3, -2, -1, 0, 1, 2, 3, 4]
The stop
argument is required, and it specifies the number at which the sequence should end. The start
and step
arguments are optional. The start
argument specifies the starting number of the sequence, and the step
argument specifies the difference between each number in the sequence. If not specified, start
defaults to 0 and step
defaults to 1.
It’s important to note that the range()
function returns a sequence of numbers, not a list. If you need to use the numbers in a list, you can use the list()
function to convert the range to a list.
# Convert the range to a list and print it
numbers = list(range(10))
print(numbers)
What’s next?
- If you found this story valuable, please consider clapping multiple times (this really helps a lot!)
- Hands-on Practice: Free Python Course — range()
- Full series: 100 Days of Python
- Previous topic: Lists
- Next topic: For loops