Python range function

Python range function is one of the most used function in Python.
range function is used to generate a sequence of numbers, so you can iterate over for loop.


Syntax

There is two type of paramters you can pass in range function.

In above function, you just need to provide stop value and list of numbers will be generated form 0 to stop.

In above function, we have three parameters.
start: start integer for the sequence.
stop: Last integer for the sequence.
Step: Difference between number in sequence.


Example

Let’s understand it with the help of example.

for num in range(10): print(num)

Output:

0
1
2
3
4
5
6
7
8
9

Print numbers with start, stop and step.

#Start is 4 and step size is 3, so you will see difference of 3 in sequence. for num in range(4,20,3): print(num)

Output:

4
7
10
13
16
19

Print numbers in reverse.

#Start is 20 and step size is 4, so you will see difference of -3 in sequence. for num in range(20,4,-3): print(num)

Output:

20
17
14
11
8
5

range function in python 2.X and 3.X

range function in python 2.X returns list of numbers but what if you have large amount of numbers, it will take huge amount of memory.
So range function in python 3.X behaves as generator, so you don’t have to worry about memory as it does not store all elements in memory.
It just stores element which are required at that instant.
Python 2.X has Xrange() function which behaves same as range in Python 3.X.
If you are using Python 2.X,then you should you xrange for generating sequence.

That’s all about Python range function.

Leave a Reply

Your email address will not be published. Required fields are marked *