Python built-in Method - range()

https‮w//:‬ww.theitroad.com

The range() function is a built-in Python method that is used to generate a sequence of numbers. It takes one to three integer arguments and returns an object that produces a sequence of integers from the start value (inclusive) to the end value (exclusive), with a step size of 1 (by default).

The syntax for the range() function is as follows:

range(stop)
range(start, stop[, step])
  • start (optional): The starting value of the sequence (default is 0).
  • stop: The ending value of the sequence.
  • step (optional): The step size between numbers (default is 1).

Here are some examples of how the range() function can be used:

>>> for i in range(5):
...     print(i)
...
0
1
2
3
4

In this example, we use the range() function to generate a sequence of integers from 0 to 4, and then use a for loop to print each value.

>>> for i in range(1, 10, 2):
...     print(i)
...
1
3
5
7
9

In this example, we use the range() function to generate a sequence of odd integers from 1 to 9, and then use a for loop to print each value.

>>> list(range(10))
[0, 1, 2, 3, 4, 5, 6, 7, 8, 9]

In this example, we use the range() function to generate a sequence of integers from 0 to 9, and then convert the sequence to a list using the list() constructor.

The range() function is a fundamental built-in method in Python that is used extensively in looping constructs and generating sequences of numbers. It is often used in conjunction with for loops, list comprehensions, and other sequence-processing constructs.