Python range() Function



The Python range() function is a built-in function that returns a immutable sequence of numbers within the specified range. This function is used to iterate or loop through a particular code block till a specified number of times.

The range() function starts iterating from 0, increments by 1 by default and stops one position before the specified end position.

Syntax

Following is the syntax of the Python range() function −

range(start, stop, step)

Parameters

The Python range() function accepts three parameters −

  • start − It is an optional parameter which specify the starting position. It must be an integer number from which

  • stop − This parameter represents the stop position.

  • step − It specifies the required number of increment between sequence.

Return Value

The Python range() function returns a new immutable sequence of numbers .

Examples

In this section, we will see some examples of range() function −

Example 1

If we pass a single argument to the range() function, it is considered the stop position. Therefore, the below Python code will display a sequence of numbers from 0 to one less than the specified number. With each iteration, the sequence will be incremented by 1.

print("The number in the given range:")
for index in range(10):
   print(index, end=" ")

When we run above program, it produces following result −

The number in the given range:
0 1 2 3 4 5 6 7 8 9 

Example 2

When we only pass two arguments to the range() function, the first one is considered the start position and the other one is the stop. In the code below, we display a sequence of numbers from 11 to 20.

print("The number in the given range:")
for index in range(11, 21):
   print(index, end=" ")

Following is an output of the above code −

The number in the given range:
11 12 13 14 15 16 17 18 19 20 

Example 3

It is also possible to assign the value of range() function to another variable as demonstrated in the below example.

rangeVar = range(5, 11)
for index in rangeVar:
  print(index)

Output of the above code is as follows −

5
6
7
8
9
10

Example 4

When three arguments are passed to the range() function, it signifies the start, end and increment value respectively. In the code below, we are printing even number between 12 to 20. Notice that the output is getting incremented by value 2.

print("Even numbers between given range:")
for index in range(12, 20, 2):
    print(index)

Following is an output of the above code −

Even numbers between given range:
12
14
16
18

Example 5

To decrement the sequence of numbers, we need to pass a negative integer value for the "step" parameter as demostrated in the below example.

print("Even numbers in decreasing order:")
for index in range(20, 11, -2):
    print(index)

Following is an output of the above code −

Even numbers in decreasing order:
20
18
16
14
12
python_built_in_functions.htm
Advertisements