How to use the range() function in Python

The ‘range()‘ function can be used to generate a sequence of numbers:

1. Generate a simple sequence of numbers:

for i in range(5):
print(i)

The result:

0
1
2
3
4

2. Specify a start value (e.g., 2) and a stop value (e.g., 6):

for i in range(2, 6):
print(i)

The result:

2
3
4
5

3. Use a step value (e.g., 2) to specify the difference between each number in the sequence:

for i in range(1, 6, 2):
print(i)

The result:

1
3
5

4. Use the ‘range()‘ function to create a list:

my_list = list(range(0, 10, 2))
print(my_list)

The result:

[0, 2, 4, 6, 8]

5. Reverse a sequence of numbers:

for i in range(5, 0, -1):
print(i)

The result:

5
4
3
2
1

Additional Topics

Leave a Comment