Python range() Function

It returns a sequence of numbers, starting from 0 by default, and increments by 1 (by default), and stops before a specified number.range() is commonly used in for looping hence, knowledge of same is key aspect when dealing with any kind of Python code. Most common use of range() function in Python is to iterate sequence type (List, string etc.. ) with for and while loop.

range() function only works with the integers i.e. whole numbers.

Syntax:

range([start,] stop [, step])

range() Parameters:

start
Optional. An integer number specifying at which position to start
stop
 Required .Endpoint of the sequence.
stepOptional. Integer value which determines the increment between each integer in the sequence

All argument must be integers. User can not pass a string or float number or any other type in a startstop and step argument of a range().

All three arguments can be positive or negative.

Example:

x = range(1, 30, 5)
for n in x:
    print(n, end = ' ')

Output: 1 6 11 16 21 26

Incrementing with the help of range() by positive step:

If we want to increment, then we need step to be a positive number.

for i in range(2, 25, 2):
    print(i, end = ' ')

Output: 2 4 6 8 10 12 14 16 18 20 22 24 26

Decrementing with the help of range() by negative step :

If we want to decrement, then we  need step to be a negative number.

for i in range(25, -6, -3):
    print(i, end =" ")
Output: 25 22 19 16 13 10 7 4 1 -2 -5

Concatenation of two range() functions:

The chain() method is used to print all the values in iterable targets one after another mentioned in its arguments.

from itertools import chain
  
print("Result")
res = chain(range(5), range(10, 20, 2))
  
for i in res:
    print(i, end=" ")

Output:  0 1 2 3 4 10 12 14 16 18

range() indexing and slicing:

Indexing

It supports both positive and negative indices.

r = range(0,10)
print(r[9])

Output: 9

Slicing

It implies accessing a portion from range().

for i in range(10)[3:8]:
    print(i, end=' ')

Output: 3 4 5 6 7

Tags