The range() is a built-in function in Python that returns the sequence of numbers between the specified range. This function is preferred over a list when we want a series of integers that needs to be generated at runtime.

Python range function:

Signature

The signature for the range() function is as shown below. However, there are two variants in the range function.

range(stop)
range(start, stop, step)

Function parameters and return type

  • There are two different ways in which this function can be used. The first one shows when we are only passing one parameter stop. The second one shows when we use starting, ending, and step. However, step is an optional parameter.
  • However, it returns a sequence of numbers between the given range.

Python range Examples:

Example 1: In this example, let us demonstrate the working of the range function with a single parameter.

#Using range
r=range(10)
# Printing the range
print (r)
#Printing range of values as tuple
print(tuple(r))

Output

range(0, 10)
(0, 1, 2, 3, 4, 5, 6, 7, 8, 9)

Example 2: In this case, we will generate a sequence of numbers with specific start and end values and step. Here, we are printing it as a list.

#Using range
r=range(111,120,2)
#Printing range and values as a list
print (r)
print(list(r))

Output

range(111, 120,2)
[111, 113, 115, 117, 119]

Example 3: For this example, we will take a string and the end value will be the length of the string.

#Initializing
s="python"
#Using range
r=range(0,len(s))
#Printing
print (r)
print(list(r))

Output

range(0, 6)
[0, 1, 2, 3, 4, 5]

Conclusion

The range() function returns the sequence of numbers between the given range of numbers.

References

Happy Learning 🙂

Leave A Comment