Overview of the range() Function in Python Programming

This blog gives a brief overview about a built-in function range in Python.

 Introduction
 
This post explains the range() function in Python. A range is a function in Python programming language that is used to generate integer values within a given range of numbers.
 
The general syntax of range() function is as follows...
 
range(<start>[,<stop>,<step>=1])
 
The range() function will generate whole numbers (integer values) starting from 0 to one less than the given stop value, in intervals of 1.
 
When we give only one parameter, the range function generates numbers from 0 to 1 less than the given value/number.
 
Example
 
range(10) the output of the range function will generate values from 0 to 9 in steps of 1.
 
When we give two parameters to the range function, it will generate from the start value to 1 less than the stop value in steps of 1. The start value must always be less than the stop value.
 
Example
 
range (5,10), the output of the range function will generate values from 5 to 9 in steps of 1.
 
How to generate a list of numbers from 5 to 15 and store it into a variable by formatting it as a list is shown in the following code:
  1. Nums = list(range(5,16));  
To display the contents of the list of numbers in the Nums variable, which is a List container object using a 'for' loop is as follows:
  1. #Advance approach by accessing each and every element and displaying it using a for-loop.  
  2. for n in Nums:  
  3. print(n);  
  4. #Accessing the contents of the Nums list object using the index values with for-loop.  
  5. for i in range(len(Nums)):  
  6. print(“Element at index :: “,i,” = “,Nums[i]);  
  7. #Accessing the contents of the Nums list object using while-loop  
  8. i=0;  
  9. while(i<len(Nums)):  
  10. print(“Element at index :: “,i,” = “,Nums[i]);  
  11. i+=1;  
To generate numbers in reverse order, here are some examples using the range function
  1. Nums = list(range(10,1,-1));  
The above Nums list object will have numbers from 10 to 0, as it will not include the stop value '1' in the above statement.
 
To display the contents of the above Nums list object, we can use any of the following looping control structures.
  1. #Using a for-loop  
  2. for n in Nums:  
  3. print(n)  
  4. #Using for-loop and accessing the elements using the index values.  
  5. for i in range(len(Nums)):  
  6. print(“Element at index :: “, i , “ = “,Nums[i]);  
  7. # Using the while loop.  
  8. i = 0  
  9. while(i<len(Nums)):  
  10. print(“Element at index “, i, “ = “, Nums[i] );  
Try to experiment with the logic to display contents of the above mentioned list from the last element to the first element.
 
If you have any questions, please send an email to govardhanraop@gmail.com