search

What is the use of the "range" function in Python?

The range() function in Python is used to generate a sequence of numbers. It is often used in for loops to iterate over a specific range of numbers. The range() function can be called with one, two, or three arguments, depending on the desired behavior.

Here's the general syntax of the range() function:

range(stop)
range(start, stop)
range(start, stop, step)
  • start (optional): Specifies the starting value of the sequence (inclusive). If not provided, it defaults to 0.
  • stop (required): Specifies the ending value of the sequence (exclusive). The sequence will go up to, but not include, this value.
  • step (optional): Specifies the step or increment value between each number in the sequence. If not provided, it defaults to 1.

The range() function returns a range object, which is an iterable sequence of numbers. To get a list of numbers from the range, you can pass it to the list() function.

Let's look at some examples to understand the usage of the range() function:

  1. Example with one argument (stop):
for num in range(5):
    print(num)

Output:

0
1
2
3
4

In this example, the range(5) generates a sequence of numbers from 0 to 4 (exclusive). The for loop iterates over this sequence, and each number is printed.

  1. Example with two arguments (start, stop):
for num in range(2, 8):
    print(num)

Output:

2
3
4
5
6
7

Here, the range(2, 8) generates a sequence of numbers from 2 to 7 (exclusive). The for loop iterates over this sequence, and each number is printed.

  1. Example with three arguments (start, stop, step):
for num in range(1, 10, 2):
    print(num)

Output:

1
3
5
7
9

In this example, the range(1, 10, 2) generates a sequence of odd numbers from 1 to 9. The for loop iterates over this sequence, and each number is printed.

The range() function is a useful tool for generating sequences of numbers and controlling the iteration process in for loops. It allows you to specify the starting point, ending point, and step size of the sequence, giving you flexibility in creating loops that suit your needs.

Related Questions You Might Be Interested