Python range() Function: Complete Usage Guide

In Python, the range() function is used to generate a series of numbers. Its basic usage is as follows:

  1. Generate numbers from 0 up to, but not including, the specified stop value.
for i in range(5):
    print(i)

Output:

0
1
2
3
4
  1. generate a sequence from start to stop
for i in range(2, 6):
    print(i)

Output:

2
3
4
5
  1. Generate a sequence of numbers beginning at ‘start’, ending at ‘stop’, and increasing by ‘step’.
for i in range(1, 10, 2):
    print(i)

Output:

1
3
5
7
9

It is important to note that the sequence generated by the range() function is an immutable sequence. If modifications need to be made to the generated sequence, it can be converted to a list.

numbers = list(range(5))
print(numbers)

Output:

[0, 1, 2, 3, 4]
bannerAds