Range:

The_ range__ type represents an immutable sequence of numbers and is commonly used for looping a specific number of times in for loops._

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

**start**

The value of the start parameter (or 0 if the parameter was not supplied)

**stop**

The value of the stop parameter

**step**

The value of the step parameter (or 1 if the parameter was not supplied).

If the step is 0, it will raise ValueError.

The arguments to the range function should be integers. (either built-in int or any object that implements the __index__ special method)

Example 1:Only the stop parameter is given.

range(10)

  • start by default will be 0 and **step **by default will be 1
  • stop is given as 10.
  • stop value is excluded. It generates value until 9 only.
  • It will return a range object containing numbers starting from 0 to 9.
  • We can convert the range object to list using list() constructor.
  • We can also iterate using for loop
r=range(10)
print (r)#Output:range(0, 10)
print (type(r))#Output:<class 'range'>
print (list(r))
#Output:[0, 1, 2, 3, 4, 5, 6, 7, 8, 9]

Example 2:Only the start and stop parameter is given.

**range(1,10)**

  • step by default will be 1
  • It will generate a sequence of numbers starting from 1 to 9.
r=range(1,10)
print (r)#Output:range(1, 10)
#Converting range object to list
print (list(r))
#Output:[1, 2, 3, 4, 5, 6, 7, 8, 9]

Example 3:start, stop and step parameter is given

range(1,10,2)

  • It will generate a sequence from** 1**, increment by 2, and will stop at 9.
r=range(1,10,2)
print (r)#Output:range(1, 10, 2)
#Converting range object to list
print (list(r))
#Output:[1, 3, 5, 7, 9]

Example 4:We can also decrement step by mentioning a negative number.

range(10,1,-2)

  • It will generate a sequence of numbers from 10, decrement by 2, and stop at 1.
  • Iterating through range object using for loop.

#python-range #python-programming #python #python3 #software-development #function

An Introduction to the Python Range Function.
1.45 GEEK