Skip to content
geeksforgeeks
  • Tutorials
    • Python
    • Java
    • Data Structures & Algorithms
    • ML & Data Science
    • Interview Corner
    • Programming Languages
    • Web Development
    • CS Subjects
    • DevOps And Linux
    • School Learning
    • Practice Coding Problems
  • Courses
    • DSA to Development
    • Get IBM Certification
    • Newly Launched!
      • Master Django Framework
      • Become AWS Certified
    • For Working Professionals
      • Interview 101: DSA & System Design
      • Data Science Training Program
      • JAVA Backend Development (Live)
      • DevOps Engineering (LIVE)
      • Data Structures & Algorithms in Python
    • For Students
      • Placement Preparation Course
      • Data Science (Live)
      • Data Structure & Algorithm-Self Paced (C++/JAVA)
      • Master Competitive Programming (Live)
      • Full Stack Development with React & Node JS (Live)
    • Full Stack Development
    • Data Science Program
    • All Courses
  • Python Tutorial
  • Interview Questions
  • Python Quiz
  • Python Glossary
  • Python Projects
  • Practice Python
  • Data Science With Python
  • Python Web Dev
  • DSA with Python
  • Python OOPs
Open In App
Next Article:
range() vs xrange() in Python
Next article icon

range() vs xrange() in Python

Last Updated : 23 Jun, 2025
Comments
Improve
Suggest changes
Like Article
Like
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().

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).

Python
# 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. 

Python
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.

Python
# 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 slowerExecution 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.

Next Article
range() vs xrange() in Python

K

kartik
Improve
Article Tags :
  • Python
Practice Tags :
  • python

Similar Reads

    Operator Overloading in Python
    Operator Overloading means giving extended meaning beyond their predefined operational meaning. For example operator + is used to add two integers as well as join two strings and merge two lists. It is achievable because '+' operator is overloaded by int class and str class. You might have noticed t
    8 min read
    Python | a += b is not always a = a + b
    In Python, a += b doesn't always behave the same way as a = a + b, the same operands may give different results under different conditions. But to understand why they show different behaviors you have to deep dive into the working of variables. before that, we will try to understand the difference b
    4 min read
    Difference between == and is operator in Python
    In Python, == and is operators are both used for comparison but they serve different purposes. The == operator checks for equality of values which means it evaluates whether the values of two objects are the same. On the other hand, is operator checks for identity, meaning it determines whether two
    4 min read
    Python | Set 3 (Strings, Lists, Tuples, Iterations)
    In the previous article, we read about the basics of Python. Now, we continue with some more python concepts. Strings in Python: A string is a sequence of characters that can be a combination of letters, numbers, and special characters. It can be declared in python by using single quotes, double quo
    3 min read
    Python String
    A string is a sequence of characters. Python treats anything inside quotes as a string. This includes letters, numbers, and symbols. Python has no character data type so single character is a string of length 1.Pythons = "GfG" print(s[1]) # access 2nd char s1 = s + s[0] # update print(s1) # printOut
    6 min read
    Python Lists
    In Python, a list is a built-in dynamic sized array (automatically grows and shrinks). We can store all types of items (including another list) in a list. A list may contain mixed type of items, this is possible because a list mainly stores references at contiguous locations and actual items maybe s
    6 min read
    Python Tuples
    A tuple in Python is an immutable ordered collection of elements. Tuples are similar to lists, but unlike lists, they cannot be changed after their creation (i.e., they are immutable). Tuples can hold elements of different data types. The main characteristics of tuples are being ordered , heterogene
    6 min read
    Python Sets
    Python set is an unordered collection of multiple items having different datatypes. In Python, sets are mutable, unindexed and do not contain duplicates. The order of elements in a set is not preserved and can change.Creating a Set in PythonIn Python, the most basic and efficient method for creating
    10 min read
    Dictionaries in Python
    Python dictionary is a data structure that stores the value in key: value pairs. Values in a dictionary can be of any data type and can be duplicated, whereas keys can't be repeated and must be immutable. Example: Here, The data is stored in key:value pairs in dictionaries, which makes it easier to
    5 min read
    Python Arrays
    Lists in Python are the most flexible and commonly used data structure for sequential storage. They are similar to arrays in other languages but with several key differences:Dynamic Typing: Python lists can hold elements of different types in the same list. We can have an integer, a string and even
    9 min read
geeksforgeeks-footer-logo
Corporate & Communications Address:
A-143, 7th Floor, Sovereign Corporate Tower, Sector- 136, Noida, Uttar Pradesh (201305)
Registered Address:
K 061, Tower K, Gulshan Vivante Apartment, Sector 137, Noida, Gautam Buddh Nagar, Uttar Pradesh, 201305
GFG App on Play Store GFG App on App Store
Advertise with us
  • Company
  • About Us
  • Legal
  • Privacy Policy
  • In Media
  • Contact Us
  • Advertise with us
  • GFG Corporate Solution
  • Placement Training Program
  • Languages
  • Python
  • Java
  • C++
  • PHP
  • GoLang
  • SQL
  • R Language
  • Android Tutorial
  • Tutorials Archive
  • DSA
  • Data Structures
  • Algorithms
  • DSA for Beginners
  • Basic DSA Problems
  • DSA Roadmap
  • Top 100 DSA Interview Problems
  • DSA Roadmap by Sandeep Jain
  • All Cheat Sheets
  • Data Science & ML
  • Data Science With Python
  • Data Science For Beginner
  • Machine Learning
  • ML Maths
  • Data Visualisation
  • Pandas
  • NumPy
  • NLP
  • Deep Learning
  • Web Technologies
  • HTML
  • CSS
  • JavaScript
  • TypeScript
  • ReactJS
  • NextJS
  • Bootstrap
  • Web Design
  • Python Tutorial
  • Python Programming Examples
  • Python Projects
  • Python Tkinter
  • Python Web Scraping
  • OpenCV Tutorial
  • Python Interview Question
  • Django
  • Computer Science
  • Operating Systems
  • Computer Network
  • Database Management System
  • Software Engineering
  • Digital Logic Design
  • Engineering Maths
  • Software Development
  • Software Testing
  • DevOps
  • Git
  • Linux
  • AWS
  • Docker
  • Kubernetes
  • Azure
  • GCP
  • DevOps Roadmap
  • System Design
  • High Level Design
  • Low Level Design
  • UML Diagrams
  • Interview Guide
  • Design Patterns
  • OOAD
  • System Design Bootcamp
  • Interview Questions
  • Inteview Preparation
  • Competitive Programming
  • Top DS or Algo for CP
  • Company-Wise Recruitment Process
  • Company-Wise Preparation
  • Aptitude Preparation
  • Puzzles
  • School Subjects
  • Mathematics
  • Physics
  • Chemistry
  • Biology
  • Social Science
  • English Grammar
  • Commerce
  • World GK
  • GeeksforGeeks Videos
  • DSA
  • Python
  • Java
  • C++
  • Web Development
  • Data Science
  • CS Subjects
@GeeksforGeeks, Sanchhaya Education Private Limited, All rights reserved
We use cookies to ensure you have the best browsing experience on our website. By using our site, you acknowledge that you have read and understood our Cookie Policy & Privacy Policy
Lightbox
Improvement
Suggest Changes
Help us improve. Share your suggestions to enhance the article. Contribute your expertise and make a difference in the GeeksforGeeks portal.
geeksforgeeks-suggest-icon
Create Improvement
Enhance the article with your expertise. Contribute to the GeeksforGeeks community and help create better learning resources for all.
geeksforgeeks-improvement-icon
Suggest Changes
min 4 words, max Words Limit:1000

Thank You!

Your suggestions are valuable to us.

What kind of Experience do you want to share?

Interview Experiences
Admission Experiences
Career Journeys
Work Experiences
Campus Experiences
Competitive Exam Experiences