PythonBuilt-in functions
range()
Creates a sequence of integers, most often for a for loop.
- Returns
- A
rangeobject, which you can iterate over.
Example
#Python
print(list(range(5)))
print(list(range(1, 6)))
print(list(range(0, 10, 3)))
print(list(range(5, 0, -1)))Resultsaved result, you can check it
[0, 1, 2, 3, 4]
[1, 2, 3, 4, 5]
[0, 3, 6, 9]
[5, 4, 3, 2, 1]
Definition and usage
#The range() function creates a sequence of consecutive integers. range(5) is the numbers from 0 to 4, range(1, 6) is from 1 to 5, and range(0, 10, 2) is every second number from 0 to 8. The end of the range is never included.
A range object does not store every number in memory, it computes them on the fly. That is why range(1_000_000) takes up the same amount of space as range(10).
A negative step lets you count down: range(10, 0, -1). To see the numbers as a list, pass the range to list().
Syntax
#Syntax
range(stop)
range(start, stop)
range(start, stop, step)Parameters
#start
int, default 0
The first number of the sequence.stop
int
The number before which the sequence ends (not included).step
int, default 1
The step between numbers. Can be negative.
More examples
#Python
for i in range(1, 4):
print(" ".join(f"{i * j:3}" for j in range(1, 6)))Resultsaved result, you can check it
1 2 3 4 5
2 4 6 8 10
3 6 9 12 15
Good practices
#- Remember that the end of the range is not included: for numbers 1 to 10, use
range(1, 11). - To loop over a list's elements, you don't need
range(len(...)). Loop over the elements themselves, or useenumerate().
Related entries
#- forA loop that goes through the successive items of a sequence or other iterable object.
- enumerate()Adds a counter to items while looping over them.
- len()Returns the number of items in a collection, or the number of characters in a string.
- list()Creates a list, either empty or from the items of another iterable.
Spotted a mistake or missing an example? Write to us.