What Is Range() Function?
It is a built-in function in python. It returns the sequences of numbers between a given range. The range() function is generally used with the for-loops. It is used when the user needs to perform an action a specific number of times. It is introduced in python 3.
range(start, stop, step)
How does It work?
Depending upon how many arguments the user passes to the function user can decide from where a series of the number will begin and where it will end. also how big the difference will be between two numbers of series. Also, keep in mind that these arguments are always integers.
Whenever the range function is called it returns an object and in turn, provides an iterator that calculates new values at each call based on arguments value. In simple terms, when a range is called it set the start, end, and step value which is by default 1. when we start iterating and use its counter variable that is initialized to 0 and increases on each iteration.
range() with stop argument
for i in range(3): print(i) output: 0 1 2
range() with start and stop argument
for i in range(1,4): print(i) output: 1 2 3
range() with start, stop, step
for i in range(6, 14, 2): print(i, end=" ") output: 6 8 10 12
these values can also be accessed by their index values. also it supports both positive and negative indexing.
num = range(5) print("First number:", num) num = range(5)[-1] print("Last number:", num) output: 0 4
Concatenating two range functions
to do so use the chain method of the itertools module.
from itertools import chain print("Concatenating two ranges:") res = chain(range(3), range(6, 10, 2)) for i in res: print(i, end=" ") output: Concatenating two ranges: 0 1 2 6 8
Testing Availability Of Element:
Range behaves like regular collection hence we can also test them for the availability of a certain value. E.g., to test if a number is part of a range, we can do this:
num = 3 print(num in range(2,5)) return true
>>> range(0, 2) == range(0, 3) False
Two different ranges that result in the same sequence will be seen as equal in Python. Here both of them have different sequences that is why it returns false.