• Home
  • Subscribe
  • Contribute Us
    • Share Your Interview Experience
  • Contact Us
  • About
    • About CSEstack
    • Campus Ambassador
  • Forum & Discus
  • Tools for Geek
  • LeaderBoard
CSEstack

What do you want to Learn Today?

  • Programming
    • Tutorial- C/C++
    • Tutorial- Django
    • Tutorial- Git
    • Tutorial- HTML & CSS
    • Tutorial- Java
    • Tutorial- MySQL
    • Tutorial- Python
    • Competitive Coding Challenges
  • CSE Subject
    • (CD) Compiler Design
    • (CN) Computer Network
    • (COA) Computer Organization & Architecture
    • (DBMS) Database Management System
    • (DS) Data Structure
    • (OS) Operating System
    • (ToA) Theory of Automata
    • (WT) Web Technology
  • Interview Questions
    • Interview Questions- Company Wise
    • Interview Questions- Coding Round
    • Interview Questions- Python
    • Interview Questions- REST API
    • Interview Questions- Web Scraping
    • Interview Questions- HR Round
    • Aptitude Preparation Guide
  • GATE 2022
  • Linux
  • Trend
    • Full Stack Development
    • Artificial Intelligence (AI)
    • BigData
    • Cloud Computing
    • Machine Learning (ML)
  • Write for Us
    • Submit Article
    • Submit Source Code or Program
    • Share Your Interview Experience
  • Tools
    • IDE
    • CV Builder
    • Other Tools …
  • Jobs

Difference Between range and xrange in Python | xrange vs range

Aniruddha Chaudhari/26781/2
CodePython

Python list is one of the very important data structures. To generate the list or sequence of elements, Python version 2 has two inbuilt handy functions called range() and xrange().

Whereas, xrange is deprecated from Python version 3.

Before going into the difference between range and xrange, let’s see what it is.

Table of Contents

  • What is range() and xrange()?
  • What is the difference between range and xrange?
    • xrange vs range | Working Functionality:
    • Which does take more memory?
    • Which is faster?
    • Deprecation of xrange() for Python 3.x
  • range() and xrange() Examples

What is range() and xrange()?

The function range and xrange generated the series of numbers. It takes 3 arguments- start, stop and step.

  • Start is the first integer value generated in the range. It is optional parameter and default value is 0.
  • Stop is the last integer value where you would like to stop iterating. It is required parameter.
  • Step is integer value by which each element is incremented. It is optional parameter and default value is 1.

All three arguments belong to the numeric data type of Python.

Syntax or range()

range(<start>,<stop>,<step>)

Syntax or xrange()

xrange(<start>,<stop>,<step>)

We can use these two built-in methods in the for-loop statement. Here is an example using range() and xrange() for iterating over the loop and printing values from 1 to 9 (9 inclusive).

for-loop using range()

for x in range(1, 10, 1): 
  print x

for-loop using xrange()

for x in xrange(1, 10, 1): 
  print x

For both codes, the output is the same.

Output:

1
2
3
4
5
6
7
8
9

Both work exactly the same functionally and gives the same output.

then…

What is the difference between range and xrange?

Even though the range and xrange give the same output, each element is evaluated differently during each iteration.

Let’s figure it out…

  • How are they different from each other?
  • Which one does take more memory?
  • Which one is faster to execute (performance)?
  • Why is xrange deprecated from Python 3.x?

xrange vs range | Working Functionality:

range():

The range is an inbuilt function that generates the list. It creates a static list before running the iteration.

Let’s take an example of range(1, 10).

Note: We are only passing two parameters. By default, the step-parameter value is 1. So, while each iteration, the value is incremented by one.

It creates the list of size 9 having elements 1 to 9 (9 inclusive) and returns the list object.

rObj = range(1, 10) 

print rObj 
#[1,2,3,4,5,6,7,8,9] 

type(rObj) 
#<type 'list'>

Related Read: 5 Major Difference Between List and Tuple in Python.

xrange():

Unlike range, xrange returns xrange sequence object.

xObj = xrange(1, 10) 

print xObj 
#xrange(1, 10) 

print type(xObj) 
#<type, 'xrange'>

It doesn’t create a list and each sequence element is evaluated lazily during each iteration. In other words, next iteration is similar to the returning last_value+1.

Taking an example of xrange(1, 10) …

It evaluates each element in the sequence and returns values from 1 to 9 (9 inclusive).

The xrange() is another generator and the value is created using a special technique called as yielding. For more detail, you can read the generator function and yield value in Python.

Which does take more memory?

As range() created a list of all the elements and save it before iterating. Whereas, xrange does not saves any element and evaluate each element during each iteration.

So, range() takes more memory to save these elements in the list.

Below is a code sample for testing. Generate the gigantic number of elements using both range and xrange. The range() will throw the MemoryError exception.

>>> xrange(int(1e15))
xrange(1000000000000000)
>>> 
>>> 
>>> range(int(1e15))
Traceback (most recent call last):
  File "", line 1, in 
MemoryError
>>> 

It is clear if you have limited memory space to run your program where you need to generate a gigantic range of elements, you should use xrange() over the range().

Which is faster?

Running xrange() is slower as compared to the range() as xrange evaluates the value of the element during each iteration. It is also called as lazy evaluation.

You can use timeit module to figure out the time required for each iteration during evaluating values for range() and xrange().

$ python -m timeit 'for i in range(1,1000000):' ' pass'
10 loops, best of 3: 28.2 msec per loop
$ python -m timeit 'for i in xrange(1,1000000):' ' pass'
100 loops, best of 3: 9.87 msec per loop

If you observe, the time required to generate an element using xrange is higher than using the range. The range() is faster than xrange().

Which one to use when?

If you are performing an action on a very large range of elements, it is good to use xrange(). It doesn’t save any elements. It just evaluates the next value whenever needed.

The xrange() is very well optimized than range().

If you need faster execution of your program, use range().

Deprecation of xrange() for Python 3.x

In Python 2.x, the xrange() requires very little memory as it doesn’t save any sequence values. Even though xrange takes more time for iteration, the performance impact is very negligible.

So, they wanted to use xrange() by deprecating range(). In Python 3.x, they removed range (from Python 2.x) and renamed xrange() as a range().

Quick Summary:

Using a range with different Python Version…

  • In Python 3.x, xrange() is removed and there is an only range()
  • range() in Python 3.x works exactly same as xrange() in Python 2.x

To make the code portable so that it should work with both Python versions, use range() instead of xrange().

range() and xrange() Examples

Example 1: Printing all the values in the range from 0 to 9.

Using range():

for i in range(10):
     print(i)

Using xrange():

for i in xrange(10):
     print(i)

Output:

0
1
2
3
4
5
6
7
8
9

In the above example, we are only passing a single parameter (stop) to the functions range() and xrange(). The default value for parameters – start and step are zero and one respectively.

Example 2: Print all the odd numbers between 1 and 10.

Using range():

for i in range(1, 10, 2):
     print(i)

Using xrange():

for i in xrange(1, 10, 2):
     print(i)

Output:

1
3
5
7
9

It also works with negative values.

Example 3: Python program to print values from -1 to -9 using range and xrange.

Using range():

for i in range(-1, -10, -1):
     print(i)

Using xrange():

for i in xrange(-1, -10, -1):
     print(i)

Output:

-1
-2
-3
-4
-5
-6
-7
-8
-9

If you are new to this portal, we have a complete Python tutorial available for FREE. Let’s start learning Python.

This is all about the difference between range and xrange in Python. Hope it clears your doubt so that you are able to make the decision which one to use.  If you have any queries, feel free to write in the comment.

Python Interview Questions eBook

Pythonrangexrange
Aniruddha Chaudhari
I am complete Python Nut, love Linux and vim as an editor. I hold a Master of Computer Science from NIT Trichy. I dabble in C/C++, Java too. I keep sharing my coding knowledge and my own experience on CSEstack.org portal.

Your name can also be listed here. Got a tip? Submit it here to become an CSEstack author.

Comments

  • Reply
    Ted
    August 24, 2017 at 5:16 pm

    You should consider taking this down, as it really isn’t current and leads the reader through a bunch of stuff, that in the end, reads the Python3 disclaimer. If you feel it is still relevant information then inform the reader this is for 2.X in the beginning and not waste their time. All that said, it is a good presentation.

    • Reply
      Aniruddha Chaudhari
      August 24, 2017 at 6:24 pm

      Thanks, Ted!

      Considering reader’s perspective it is really a good suggestion.
      I have updated the post and mentioned as xrange is deprecated from Python 3 at the beginning.
      Hope this helps.

      Happy Pythoning!

Leave a Reply Cancel reply

Basic Python Tutorial

  1. Python- Tutorial Overview
  2. Python- Applications
  3. Python- Setup on Linux
  4. Python- Setup on Windows
  5. Python- Basic Syntax
  6. Python- Variable Declaration
  7. Python- Numeric Data Types
  8. Python- NoneType
  9. Python- if-else/elif
  10. Python- for/while else
  11. Python- User Input
  12. Python- Multiline User Input
  13. Python- String Formatting
  14. Python- Find Substring in String
  15. Python- Bitwise Operators
  16. Python- Range Function
  17. Python- List
  18. Python- List Vs Tuple
  19. Python- Compare Two Lists
  20. Python- Sorting List
  21. Python- Delete Element from List
  22. Python- Dictionary
  23. Python- ‘is’ vs ‘==’
  24. Python- Mutable vs Immutable
  25. Python- Generator & Yield
  26. Python- Fibonacci Generator
  27. Python- Assert Statement
  28. Python- Exception Handling 
  29. Python- RegEx
  30. Python- Lambda Function
  31. Python- Installing Modules
  32. Python- Important Modules
  33. Python- Find all Installed Modules
  34. PyCharm- IDE setup
  35. Python- File Handling
  36. Python- Monkey Patching
  37. Python- Decorators
  38. Python- Instance vs Static vs Class Method
  39. Python- Name Mangling
  40. Python- Working with GUI
  41. Python- Read Data from Web URL
  42. Python- Memory Management
  43. Python- Virtual Environment
  44. Python- Calling C Function

Python Exercise

  1. Python- Tricky Questions
  2. Python- Interview Questions (60+)
  3. Python- Project Ideas (45+)
  4. Python- MCQ Test Online
  5. Python- Coding Questions (50+)
  6. Python- Competitive Coding Questions (20+)

Python String

  1. Reverse the String
  2. Permutations of String
  3. Padding Zeros to String/Number

Python List

  1. Randomly Select Item from List
  2. Find Unique Elements from List
  3. Are all Elements in List Same?

Python Dictionary

  1. Set Default Value in Dictionary
  2. Remove all 0 from a dictionary

File Handling

  1. Python- Read CSV File into List
  2. Check if the File Exist in Python
  3. Find Longest Line from File

Compilation & Byte Code

  1. Multiple Py Versions on System
  2. Convert .py file .pyc file
  3. Disassemble Python Bytecode

Algorithms

  1. Sorting- Selection Sort
  2. Sorting- Quick Sort

Other Python Articles

  1. Clear Py Interpreter Console
  2. Can I build Mobile App in Python?
  3. Extract all the Emails from File
  4. Python Shell Scripting

© 2022 – CSEstack.org. All Rights Reserved.

  • Home
  • Subscribe
  • Contribute Us
    • Share Your Interview Experience
  • Contact Us
  • About
    • About CSEstack
    • Campus Ambassador
  • Forum & Discus
  • Tools for Geek
  • LeaderBoard