Python have two built-in functions which are useful to generate a sequence of numbers. These two functions are useful when you want to do iteration using for loop. Though both of the functions do same work like generating sequence but the way work is totally different. In this post we will see syntax, how to use them and difference between those two. In one short xrange is superior to range when we consider memory usage.
Python range and xrange function syntax:
range(optional-start, last, optional-step)
xrange(optional-start, last, optional-step)
If you see both functions syntax is same and optional-start and optional-step are optional arguments for these functions. when we use them with for loop they give the same output as shown below.
For range function:
>>> for i in range(10): ... print i ... 0 1 2 3 4 5 6 7 8 9
For xrange:
>>> for i in xrange(10): ... print i ... 0 1 2 3 4 5 6 7 8 9 >>>
Using xrange is safe when dealing with larger numbers, observe below screen shots to see how memory is used for both functions. The range python function create a list with elements equal to number we given to that range where as xrange create one element at any given time. This saves use to reduce the usage of RAM.
With xrange the memory usage is in control from below screen shot where as with range function, the memory hikes it self to run a simple for loop program from below screen shots.
Example2: Creating a stepped range of elements. Create numbers from 10 to 100 with a step of 5
>>> range(10,100,5) [10, 15, 20, 25, 30, 35, 40, 45, 50, 55, 60, 65, 70, 75, 80, 85, 90, 95] >>>
For using xrange we have to depend on for loop, direct execution will not give any output as at any given time only one element is available.
>>> xrange(10,100,5) xrange(10, 100, 5) >>> for i in xrange(10,100,5): ... print i ... 10 15 20 25 30 35 40 45 50 55 60 65 70 75 80 85 90 95 >>>
Hope this helps to understand difference between range and xrange python functions.
Complete python built-in function list.
Latest posts by Surendra Anne (see all)
- Docker: How to copy files to/from docker container - June 30, 2020
- Anisble: ERROR! unexpected parameter type in action:
Fix - June 29, 2020 - FREE: JOIN OUR DEVOPS TELEGRAM GROUPS - August 2, 2019
- Review: Whizlabs Practice Tests for AWS Certified Solutions Architect Professional (CSAP) - August 27, 2018
- How to use ohai/chef-shell to get node attributes - July 19, 2018