Do you remember we used the Python range function while learning a loop? Let me remind you of an example.
for i in range(5): print(i) |
The range function is used to create a list of numbers on the basis of a number given by the user. The user gives a starting and ending number. If the user only mentions one number as in the above example then 0 is considered as the starting number and the number given by the user is considered as the ending number.
There is a third input that a user can mention while calling the range function named “step”. The step is the increment number. By default, the step is 1. Let’s take a look at examples.
Using Start, Stop and Step in Range
In the table of two, the starting number is 2 ending number is 20 and the step size is 2.
Let write a python for loop to print this table.
for i in range(2,21,2): print(i) |
The following is the output.
Reverse Range
We can also the range function to create the numbers in reverse order.
Let’s take a look at an example.
for i in range(10,2,-2): print(i) |
floating numbers in range() function
Python Range function does not accept the float numbers. If you try to use a float number then you will receive a TypeError.
Creating List using the Range function
Suppose you need a list of numbers from 1 to 10 or the result of two’s table stored in the list.
Let’s take a look at how to create it.
num = list(range(1,11)) print(num) two_table = list(range(2,21,2)) print(two_table) |