How to use range() function in python.

Shiva Burade
2 min readJan 18, 2022

Let’s say you want to create a list of numbers starting from n to m. You can create a function that can achieve the task. For example, a function similar to this can generate list of numbers from n to m.

def sample_range(start, end):
nums = []
while start < end:
nums.append(start)
start += 1
return nums

But this function is not very customizable, if you want to create list of number starting from 10 to -10, that means in reverse order then this function will not be useful. Or, if you want to generate a list of numbers starting from 10 to 20 with a difference of 2 between numbers. i.e [10, 12, 14, etc] then also this function will not be useful. Of course you can write your own function but python provides an in-built function which does all the hard-work for us.

range(start, stop, step)
start - starting number of your sequence. Default is 0.
stop - last number - 1 of your sequence. This is a required parameter.
step - to increment/decrement values present in your sequence. Default is 1.

range() function returns an instance of <class ‘range’> which can be easily casted into list, set, tuple, iterable etc.

> type(range(10)) 
<class 'range'>
> range(10)
range(0, 10)
> list(range(10))
[0, 1, 2, 3, 4, 5, 6, 7, 8, 9]

Let’s look at some examples

  1. Generate sequence of numbers from 0 to 10.
print(list(range(11)))
output: [0, 1, 2, 3, 4, 5, 6, 7, 8, 9]

As you can notice, range is not inclusive of stop. If you use range(5) then range will include numbers till 4.

2. Generate sequence of numbers from 10 to 15.

print(list(range(10, 16)))
output: [10, 11, 12, 13, 14, 15]

3. Generate sequence of number from 10 to 20, keeping a difference of 2 between numbers.

print(list(range(10, 20, 2)))
output: [10, 12, 14, 16, 18]

4. Generate sequence of numbers from 20 to 10.

print(list(range(20, 10, -1)))
output: [20, 19, 18, 17, 16, 15, 14, 13, 12, 11]

I hope now you have a clear understanding of how to use range in python.

--

--

Shiva Burade

Hello, I am software engineer by profession. I write about technology and programming tutorials.