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 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.
Latest posts by Surendra Anne (see all)
- 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
- wget download a file to a directory in Linux/Unix - June 4, 2018
- GIT: How to compare two GIT branches? - June 3, 2018
- Online training on Linux Bash shell scripting - February 8, 2018