How to Create a Range of Numbers in Python
The range() function in Python is used to generate a sequence of numbers.
It is primarily used with a for loop to repeat a block of code a specified number of times or generate a sequence of consecutive numbers.
How do you use the range function?
The range() function can be used in three different ways as shown below.
Single Argument
range(n) creates a sequence of numbers from 0 to n-1.
For example, range(5) generates numbers from 0 to 4 (0, 1, 2, 3, 4).
for i in range(5):
print(i)
Two Arguments
range(start, stop, step) generates numbers starting from start, ending before stop, with a specified step
For example, range(1, 5) generates numbers from 1 to 4 (1, 2, 3, 4).
for i in range(1, 5):
print(i)
Three Arguments
range(start, stop, step) generates numbers from start to stop-1 with a step interval.
For example, range(1, 10, 2) generates numbers from 1 to 9, increasing by 2 each time (1, 3, 5, 7, 9).
for i in range(1, 10, 2):
print(i)
As shown, the range function is useful in a for loop to repeat a block of code a specific number of times or generate a sequence of numbers.
for i in range(100):
... # Repeat code block 100 times
Want to learn more?
Join CodeFriends Plus membership or enroll in a course to start your journey.