Open In App

range() vs xrange() in Python

Last Updated : 23 Aug, 2023
Improve
Improve
Like Article
Like
Save
Share
Report

The range() and xrange() are two functions that could be used to iterate a certain number of times in for loops in Python. In Python3, there is no xrange, but the range function behaves like xrange in Python2. If you want to write code that will run on both Python2 and Python3, you should use range(). Both are implemented in different ways and have different characteristics associated with them. The points of comparison are:

  • Return Type
  • Memory
  • Operation Usage
  • Speed

Python range() function

The Python range() function returns a sequence of numbers, in a given range. The most common use of it is to iterate sequences on a sequence of numbers using Python loops.

Python xrange() function

The xrange() function in Python is used to generate a sequence of numbers, similar to the Python range() function. The Python xrange() is used only in Python 2.x whereas the range() function in Python is used in Python 3.x. 

Return Type in range() vs xrange()

This xrange() function returns the generator object that can be used to display numbers only by looping. The only particular range is displayed on demand and hence called “lazy evaluation“, whereas, in Python range() function returns a range object (a type of iterable).

Python3




# initializing a with range()
a = range(1, 10000)
 
# initializing a with xrange()
x = xrange(1, 10000)
 
# testing the type of a
print("The return type of range() is : ")
print(type(a))
 
# testing the type of x
print("The return type of xrange() is : ")
print(type(x))


Output:

The return type of range() is : 
<type 'list'>
The return type of xrange() is :
<type 'xrange'>

Speed of xrange() and range() Function

The variable storing the range created by range() takes more memory as compared to the variable storing the range using xrange(). The basic reason for this is the return type of range() is list and xrange() is xrange() object. 

Python3




import sys
 
# initializing a with range()
a = range(1,10000)
 
# initializing a with xrange()
x = xrange(1,10000)
 
# testing the size of a
# range() takes more memory
print ("The size allotted using range() is : ")
print (sys.getsizeof(a))
 
# testing the size of x
# xrange() takes less memory
print ("The size allotted using xrange() is : ")
print (sys.getsizeof(x))


Output: 

The size allotted using range() is : 
80064
The size allotted using xrange() is :
40

Operations Usage of xrange() and range() Function

A range() returns the list, all the operations that can be applied on the list can be used on it. On the other hand, as xrange() returns the xrange object, operations associated with the list cannot be applied to them, hence a disadvantage.

Python3




# initializing a with range()
a = range(1,6)
 
# initializing a with xrange()
x = xrange(1,6)
 
# testing usage of slice operation on range()
# prints without error
print ("The list after slicing using range is : ")
print (a[2:5])
 
# testing usage of slice operation on xrange()
# raises error
print ("The list after slicing using xrange is : ")
print (x[2:5])


Error: 

Traceback (most recent call last):
File "1f2d94c59aea6aed795b05a19e44474d.py", line 18, in
print (x[2:5])
TypeError: sequence index must be integer, not 'slice'

Output: 

The list after slicing using range is : 
[3, 4, 5]
The list after slicing using xrange is :

Difference between range() and xrange() in Python

Because of the fact that xrange() evaluates only the generator object containing only the values that are required by lazy evaluation, therefore is faster in implementation than range().

Important Points: 

  • If you want to write code that will run on both Python 2 and Python 3, use range() as the xrange function is deprecated in Python 3.
  • range() is faster if iterating over the same sequence multiple times.
  • xrange() has to reconstruct the integer object every time, but range() will have real integer objects. (It will always perform worse in terms of memory, however)

range()

xrange()

Returns a list of integers. Returns a generator object.
Execution speed is slower Execution speed is faster.
Takes more memory as it keeps the entire list of elements in memory. Takes less memory as it keeps only one element at a time in memory.
All arithmetic operations can be performed as it returns a list. Such operations cannot be performed on xrange().
In python 3, xrange() is not supported. In python 2, xrange() is used to iterate in for loops.


Previous Article
Next Article

Similar Reads

Python - Test if List contains elements in Range
A lot of times, while working with data, we have a problem in which we need to make sure that a container or a list is having elements in just one range. This has application in Data Domains. Let's discuss certain ways in which this task can be performed. Method #1 : Using loop This is brute force method in which this task can be performed. In this
5 min read
Python range() Method
There are many iterables in Python like list, tuple etc. range() gives another way to initialize a sequence of numbers using some conditions.range() is commonly used in for looping hence, knowledge of same is key aspect when dealing with any kind of Python code. Syntax : range(start, stop, step)Parameters : start : Element from which sequence const
3 min read
Python | Numbers in a list within a given range
Given a list, print the number of numbers in the given range. Examples: Input : [10, 20, 30, 40, 50, 40, 40, 60, 70] range: 40-80 Output : 6 Input : [10, 20, 30, 40, 50, 40, 40, 60, 70] range: 10-40 Output : 4 Multiple Line Approach:Traverse in the list and check for every number. If the number lies in the specified range, then increase the counter
6 min read
Python | Count unset bits in a range
Given a non-negative number n and two values l and r. The problem is to count the number of unset bits in the range l to r in the binary representation of n, i.e, to count unset bits from the rightmost lth bit to the rightmost rth bit. Examples: Input : n = 42, l = 2, r = 5 Output : 2 (42)10 = (101010)2 There are '2' unset bits in the range 2 to 5.
2 min read
Python range() function
The Python range() function returns a sequence of numbers, in a given range. The most common use of it is to iterate sequences on a sequence of numbers using Python loops. Example In the given example, we are printing the number from 0 to 4. C/C++ Code for i in range(5): print(i, end=&quot; &quot;) print() Output: 0 1 2 3 4 Syntax of Python range()
6 min read
Python | Count set bits in a range
Given a non-negative number n and two values l and r. The problem is to count the number of set bits in the range l to r in the binary representation of n, i.e, to count set bits from the rightmost lth bit to the rightmost rth bit. Constraint: 1 &lt;= l &lt;= r &lt;= number of bits in the binary representation of n. Examples: Input : n = 42, l = 2,
2 min read
Python | Generate random numbers within a given range and store in a list
Given lower and upper limits, Generate random numbers list in Python within a given range, starting from 'start' to 'end', and store them in the list. Here, we will generate any random number in Python using different methods. Examples: Input: num = 10, start = 20, end = 40 Output: [23, 20, 30, 33, 30, 36, 37, 27, 28, 38] Explanation: The output co
5 min read
Python List Comprehension | Three way partitioning of an array around a given range
Given an array and a range [lowVal, highVal], partition the array around the range such that array is divided in three parts. 1) All elements smaller than lowVal come first. 2) All elements in range lowVal to highVal come next. 3) All elements greater than highVal appear in the end. The individual elements of three sets can appear in any order. Exa
3 min read
Python | Contiguous Boolean Range
Sometimes, we come across a problem in which we have a lot of data in a list in the form of True and False value, this kind of problem is common in Machine learning domain and sometimes we need to know that at a particular position which boolean value was present. Let's discuss certain ways in which this can be done. Method #1 : Using enumerate() +
6 min read
Python program to print all negative numbers in a range
Given the start and end of a range, write a Python program to print all negative numbers in a given range. Examples: Input: a = -4, b = 5 Output: -4, -3, -2, -1 Input: a = -3, b= 4 Output: -3, -2, -1 Method: Print all the negative numbers using a single-line solution. Print all negative numbers using for loop. Define the start and end limits of the
4 min read
Article Tags :
Practice Tags :
three90RightbarBannerImg