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:
- 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:
-
- for n in Nums:
- print(n);
-
- for i in range(len(Nums)):
- print(“Element at index :: “,i,” = “,Nums[i]);
-
- i=0;
- while(i<len(Nums)):
- print(“Element at index :: “,i,” = “,Nums[i]);
- i+=1;
To generate numbers in reverse order, here are some examples using the range function
- 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.
-
- for n in Nums:
- print(n)
-
- for i in range(len(Nums)):
- print(“Element at index :: “, i , “ = “,Nums[i]);
-
- i = 0
- while(i<len(Nums)):
- 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.