What’s range() and xrange() in Python?
range() and xrange() are both built-in functions in Python which in a given range are used to generate whole numbers or integers. There is no operational difference between range() and xrange(). Both of them produce a list of numbers for us to use.
>>range(1, 9, 3)
[1, 4, 7]
>>xrange(1, 9, 3)
[1, 4, 7]
So, a comparison between the two functions range() and xrange() would be more meaningful if we are talking about their functioning in Python 2.x and Python 3. Now let us look where they differ.
syntax of range():
xrange(start, stop, step)
Syntax of xrange():
range(start, stop, step)
Start: The first value in the list of integers. If this value is not mentioned, it gets initialized as 0. Initialization of it is optional.
Stop: It is the last second element in the list of integers. Initialization of it is mandatory.
Step: It is the value by which each element in the list gets incremented. If this value is not mentioned, it gets initialized as 0. Initialization of it is optional.
The xrange() function returns us an xrange object. It performs lazy evaluation, i.e. only a particular range is displayed. It keeps the arguments and produces numbers upon calling, and these numbers can only be displayed by using a loop. Unlike range(), it doesn’t fetch us all the numbers at once.
We can perform iteration, indexing and also use the len() method using an xrange() object. It computes the next value only when needed using an xrange object and does not create a list of all values like range().
One advantage of this function is that an xrange() object will always use the same amount of memory without getting affected by the range mentioned. xrange() performs great, especially when we are iterating over a large range.
>>> a = xrange(1, 100, 1) >>> type(a) <type 'xrange'> >>> a #indexing 1 >>> for x in a: #iterating print(x)
Note: xrange() can’t be used in all cases where we would need a list. For example, it doesn’t support slicing or any list methods.
In Python 2.x, range() function creates a list of given start and stop values. So, range(1, 1000000) creates a list in memory with 999999 elements. When we have large ranges, this operation will become tedious and more memory consuming. The range() function returns us a list of numbers.
In Python 3, range() function’s working is similar or equivalent to python’s 2.x xrange() function, i.e. to get a list. If we want to generate a list, the following syntax is used.
Note: If you want to write a code that will run on both Python 2.x and Python 3, you cannot use xrange(). Also xrange() in Python 3 doesn’t exist, as the xrange() function in Python 2 was renamed as range() in Python 3.
If we are iterating over the same sequence, i.e. list, for multiple times, the range() function works faster than xrange(). The xrange() function rebuilds the object(integer) every time, but range() will have real integer objects.