Python: range() function
range() is a built in function in python3 which is used to generate a number of sequence.
This function is used for looping or when we need to iterate sequence of List, string etc.
There are three parts is this function:
1. Start
2. Stop
3. Step
range(start, stop, step) - here in the start we have to define from where we want to start. If we assign nothing in the start point then it will always start from 0 which is the default value of this function.
Then we have to define when to stop. For example, if we assign 10 here. Then the loop will iterate 10 times (0–9). It will always stop before its given value.
Such as, if I assign start=0, stop=10, then the loop will iterate (0–9), which just before 10. Actually, if we want to start from 0, then we don’t need to write 0 as a parameter because the default value is 0.
And the third part of this range() function is step which is the increment part. That means how many times we need to increment.
The above explanation is about a basic theory of range() function and its parameter. Let’s go through the example:
In the above code snippet, we can see that if we provide one parameter in range() function, then it will take as its stop parameter that means where to stop. Its default start parameter value is 0 and step parameter value is 1. That’s why the variable i is starts from 0 and stops just before 10 and increment 1 times.
In the above code snippet, we can see that if we provide 2 parameter then this function take the first value as start, second value as stop. That’s why the iteration starts from 2 and stops before 10.
From the above code, we see that, here the value of start = 2, stop = 10 and step = 1. As the default value of step is 1, so it is not necessary to mention in range() function. But if we need to increment 2 times, then we have to provide 2 in the parameter.
For example,
Here, the value of step is 2. That’s why i starts from 1 and increment by 2. And prints 1, 3, 5, 7, 9.
Key points of above code:
If we use for one argument, then it will be range(stop)
If we use for two argument, then it will be range(start, stop)
If we use for three argument, then it will be range(start, stop, step)
In the range() function, step part is also use for decrement. Next code snippet is for decrement.
Here, iteration starts from 10 and prints the value by decrementing by 1.
It is also possible to concatenate two range, but we have to import chain. For example:
The above code snippet is about indexing. We provide a range (0–4) using range() function and it prints the index number which is 3. If we provide [5], it will show an error, because 5 is not in the range. It is from 0–4. For example,