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.
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.
range([start], stop[, step])
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.
Let’s understand it with the help of example.
for num in range(10): print(num)
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)
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)
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.