TechBeamersTechBeamers
  • Learn ProgrammingLearn Programming
    • Python Programming
      • Python Basic
      • Python OOP
      • Python Pandas
      • Python PIP
      • Python Advanced
      • Python Selenium
    • Python Examples
    • Selenium Tutorials
      • Selenium with Java
      • Selenium with Python
    • Software Testing Tutorials
    • Java Programming
      • Java Basic
      • Java Flow Control
      • Java OOP
    • C Programming
    • Linux Commands
    • MySQL Commands
    • Agile in Software
    • AngularJS Guides
    • Android Tutorials
  • Interview PrepInterview Prep
    • SQL Interview Questions
    • Testing Interview Q&A
    • Python Interview Q&A
    • Selenium Interview Q&A
    • C Sharp Interview Q&A
    • PHP Interview Questions
    • Java Interview Questions
    • Web Development Q&A
  • Self AssessmentSelf Assessment
    • Python Test
    • Java Online Test
    • Selenium Quiz
    • Testing Quiz
    • HTML CSS Quiz
    • Shell Script Test
    • C/C++ Coding Test
Search
  • Python Multiline String
  • Python Multiline Comment
  • Python Iterate String
  • Python Dictionary
  • Python Lists
  • Python List Contains
  • Page Object Model
  • TestNG Annotations
  • Python Function Quiz
  • Python String Quiz
  • Python OOP Test
  • Java Spring Test
  • Java Collection Quiz
  • JavaScript Skill Test
  • Selenium Skill Test
  • Selenium Python Quiz
  • Shell Scripting Test
  • Latest Python Q&A
  • CSharp Coding Q&A
  • SQL Query Question
  • Top Selenium Q&A
  • Top QA Questions
  • Latest Testing Q&A
  • REST API Questions
  • Linux Interview Q&A
  • Shell Script Questions
© 2024 TechBeamers. All Rights Reserved.
Reading: Python XRange vs Range
Font ResizerAa
TechBeamersTechBeamers
Font ResizerAa
  • Python
  • SQL
  • C
  • Java
  • Testing
  • Selenium
  • Agile Concepts Simplified
  • Linux
  • MySQL
  • Python Quizzes
  • Java Quiz
  • Testing Quiz
  • Shell Script Quiz
  • WebDev Interview
  • Python Basic
  • Python Examples
  • Python Advanced
  • Python OOP
  • Python Selenium
  • General Tech
Search
  • Programming Tutorials
    • Python Tutorial
    • Python Examples
    • Java Tutorial
    • C Tutorial
    • MySQL Tutorial
    • Selenium Tutorial
    • Testing Tutorial
  • Top Interview Q&A
    • SQL Interview
    • Web Dev Interview
  • Best Coding Quiz
    • Python Quizzes
    • Java Quiz
    • Testing Quiz
    • ShellScript Quiz
Follow US
© 2024 TechBeamers. All Rights Reserved.
Python BasicPython Tutorials

Python XRange vs Range

Last updated: Sep 28, 2023 9:03 pm
By Meenakshi Agarwal
Share
8 Min Read
python xrange vs. range function
python xrange vs. range function
SHARE

In Python programming, we have two range() and xrange() functions that generate the integer numbers from a given start and stop value. Here, we are discussing the main differences between Python xrange and range functions.

Contents
What are Python range and xrange functions?The difference between Python xrange and rangeOperational differenceReturn values and typePython xrange vs. range – compare the speedCalculate the time of range()What to prefer xrange or range?Where should we use xrange()?Where should we use range()?Python xrange vs. range compatibility

Python xrange() vs range()

The range() function has already replaced xrange(), but it is still good to learn the differences and similarities between these two. It is helpful when you get to work on a legacy project developed in Python 2 and using xrange().

What are Python range and xrange functions?

In Python 2, we had the two underlying methods to generate a list of integers within a given range.

  • range()
  • xrange()

However, in Python 3, range() was decommissioned, and xrange() was renamed to range().

Hence, in Python 3, we get a single function that could produce the numbers from a given range. It was none other than the Python range function.

The range() function in Python 3 is just a re-implementation of the xrange() of Python 2. It actually works the same way as the xrange does.

If you are using Python 2, then only the difference between xrange() and range() is meaningful to you.

The difference between Python xrange and range

The two range functions have many different traits. These could relate to performance, memory consumption, speed, and internal design. Each of these has its implementation differently. Now, let’s review each such differences one by one.

Operational difference

In most cases, both xrange and range operate precisely in the same way. They both give a way to produce a list of numbers for you to use.

Hence, we can say that both are similar in terms of functionality. Let’s see some examples now:

The expression range (1, 7, 2) will produce [1, 3, 5] and xrange(1, 7, 2) will produce [1, 3, 5]. Hence, you can conclude that they have a similar execution pattern and output.

Return values and type

It is the primary source of difference between Python xrange and range functions.

The range() returns a list-type object. For example, the expression range(1, 100, 1) will produce a 99 int numbers range. It gets all the numbers in one go.

>>> r = range(1, 100, 1)
>>> type(r)
<type 'list'>
>>> len(r)
99

On the other hand, the xrange() provides results as an xrange object. It performs a lazy evaluation. It keeps the arguments and produces numbers on call. Unlike range(), it avoids getting all the numbers in one go.

The xrange object allows iteration, indexing, and the len() method. You can have a for loop to traverse it and get the numbers in every iteration.

>>> xr = xrange(1, 100, 1)
>>> type(xr)
<type 'xrange'>
>>> xr[0]
1
>>> for it in xr:
...    print(it)
...
1
2
3
...
99

Also Check: Print Alphabet Pattern “A” Using Python Range()

Python xrange vs. range – compare the speed

We have got a timeit module in Python to capture the execution time of any function. We’ll use it in our test and see which of the xrange or range is faster.

Calculate the time of range()

We executed range() in our test three times, see the below example and the time it took for execution:

>>> import timeit
>>> timeit.timeit('"-".join(str(num) for num in range(10000))', number=10000)
22.56510010000011
>>> timeit.timeit('"-".join(str(num) for num in range(10000))', number=10000)
22.796818399999893
>>> timeit.timeit('"-".join(str(num) for num in range(10000))', number=10000)
24.003325399999994

Again, we ran the same test with xrange() three times and recorded their execution time.

>>> timeit.timeit('"-".join(str(num) for num in xrange(10000))', number=10000)
20.672853799999984
>>> timeit.timeit('"-".join(str(num) for num in xrange(10000))', number=10000)
20.471903500000053
>>> timeit.timeit('"-".join(str(num) for num in xrange(10000))', number=10000)
20.15995029999999

From the above tests and results, you can assess that xrange is faster than the standard range function.

  • While using xrange, you would have noticed that it doesn’t produce a static list as the range() function does. Instead, it is more like a generator that gives values on demand. This technique is popularly known as yielding.
  • The range() function gets all the numbers at once before executing any instruction in the loop.

Here are some facts for your reference:

  • The primary issue with the standard range() function is that it consumes a significant amount of memory, especially for a bigger range of numbers.
  • xrange() function always provides the next element on demand. It means that only one item exists in memory at a time. Hence, it consumes less memory.

What to prefer xrange or range?

It’s a tradeoff between an instant result or a segmented output. With xrange, we get a speedier response; also, its consumption of memory is lower.

Hence, it is evident that Python xrange has an edge over the traditional range() function. Let’s now look at some cases to understand which of these methods fits where.

Where should we use xrange()?

  • When the range has a broader scope, there we recommend using the xrange(). It will improve speed and require less memory.
  • If you plan to run on smaller devices (which have memory constraints), then with xrange(), you may not see buffer issues.
  • Since xrange() evaluates items with a slack, you may break them at any point when needed. In this way, you can avoid creating the entire list.

Where should we use range()?

  • When you have to traverse the list frequently, then it’s better to use range(). With xrange(), it would be an overhead to instantiate an integer object for every indexing request.
  • If you are not looking for a wide range, then using the range() function is the right idea.
  • Since the range method returns a list object, you can utilize all of its functions. On the contrary, xrange provides a bare integer object which requires indexing.
  • Interestingly, if you wish to keep your Python 2 code compatible with version 3, then you should prefer using the range method.

Python xrange vs. range compatibility

In Python 3, the xrange function doesn’t exist, whereas it provides the range() function. The reality is that “xrange” has got its name changed to “range” in Python 3.

So, if you step to call xrange() in Python 3, it will raise the below error.

NameError: name ‘xrange’ is not defined

Also, if you opt to import the xrange, even then the following error will occur.

ImportError: No module named ‘xrange’

Hence, you may decide to use range() instead of xrange() to maintain compatibility across different versions.

You Might Also Like

How to Connect to PostgreSQL in Python

Generate Random IP Address (IPv4/IPv6) in Python

Python Remove Elements from a List

How to Use Extent Report in Python

10 Python Tricky Coding Exercises

Meenakshi Agarwal Avatar
By Meenakshi Agarwal
Follow:
Hi, I'm Meenakshi Agarwal. I have a Bachelor's degree in Computer Science and a Master's degree in Computer Applications. After spending over a decade in large MNCs, I gained extensive experience in programming, coding, software development, testing, and automation. Now, I share my knowledge through tutorials, quizzes, and interview questions on Python, Java, Selenium, SQL, and C# on my blog, TechBeamers.com.
Previous Article Generate float range of numbers in Python Generate Floating Point Range in Python
Next Article Python sorted function with examples Python Sorted() Function

Popular Tutorials

SQL Interview Questions List
50 SQL Practice Questions for Good Results in Interview
SQL Interview Nov 01, 2016
Demo Websites You Need to Practice Selenium
7 Sites to Practice Selenium for Free in 2024
Selenium Tutorial Feb 08, 2016
SQL Exercises with Sample Table and Demo Data
SQL Exercises – Complex Queries
SQL Interview May 10, 2020
Java Coding Questions for Software Testers
15 Java Coding Questions for Testers
Selenium Tutorial Jun 17, 2016
30 Quick Python Programming Questions On List, Tuple & Dictionary
30 Python Programming Questions On List, Tuple, and Dictionary
Python Basic Python Tutorials Oct 07, 2016
//
Our tutorials are written by real people who’ve put in the time to research and test thoroughly. Whether you’re a beginner or a pro, our tutorials will guide you through everything you need to learn a programming language.

Top Coding Tips

  • PYTHON TIPS
  • PANDAS TIPSNew
  • DATA ANALYSIS TIPS
  • SELENIUM TIPS
  • C CODING TIPS
  • GDB DEBUG TIPS
  • SQL TIPS & TRICKS

Top Tutorials

  • PYTHON TUTORIAL FOR BEGINNERS
  • SELENIUM WEBDRIVER TUTORIAL
  • SELENIUM PYTHON TUTORIAL
  • SELENIUM DEMO WEBSITESHot
  • TESTNG TUTORIALS FOR BEGINNERS
  • PYTHON MULTITHREADING TUTORIAL
  • JAVA MULTITHREADING TUTORIAL

Sign Up for Our Newsletter

Subscribe to our newsletter to get our newest articles instantly!

Loading
TechBeamersTechBeamers
Follow US
© 2024 TechBeamers. All Rights Reserved.
  • About
  • Contact
  • Disclaimer
  • Privacy Policy
  • Terms of Use
TechBeamers Newsletter - Subscribe for Latest Updates
Join Us!

Subscribe to our newsletter and never miss the latest tech tutorials, quizzes, and tips.

Loading
Zero spam, Unsubscribe at any time.
x