'Coding has over 700 languages', '67% of programming jobs aren’t in the technology industry', 'Coding is behind almost everything that is powered by electricity'
Last Updated: Dec 31, 2023
Easy

range vs xrange in Python

gp-icon
Basics of python
Free guided path
7 chapters
99+ problems
gp-badge
Earn badges and level up

Introduction

Hey Ninjas. You must have used the range() and xrange() functions in Python to generate a sequence of numbers. Have you ever thought they have some differences? How you'll handle memory usage and performance using range vs xrange in Python?

og image

In this article, we'll talk about range vs xrange in Python and how both functions work. So let's take a closer look at range vs xrange in Python.

Range in Python

range() is a built-in and convenient function in Python. Creating a sequence of numbers using the range() function is relatively easy. You can use the range() function with loops to go through the list of numbers. You can use the range() function to produce a series of characters as ASCII codes. It can be helpful for you to make a sequence of decimal numbers. It is a very memory-saving function because it creates an output list with one entry for each number for the range you input. You can prefer using range() when working with a small range. It generates the numbers on the fly instead of pre-allocating memory for all the numbers in the sequence. On the fly means it calculates the numbers in the sequence according to the user's need. It does not pre-allocate all the necessary memory initially. 

Syntax

range([beginning], terminate, [increment])

Parameters

Here the square brackets indicate optional parameters.

  • beginning: It describes the starting value of the sequence.
     
  • terminate: is the end value of the series (exclusive). It is required to generate a range.
     
  • increment: It represents the step size between the values in the series.
     

You can omit the beginning or increment parameters using the default values of 0 and 1, respectively. 

Return Type

The return type of the range() function in Python is an object of the type range. This immutable sequence type represents a range of numbers and is not a list. 

Remember that in Python 2, the range() function does return a list.

Time Complexity 

  • O(1):The time complexity of the range() function in Python is O(1) for simple member checks with an integer. 
     
  • O(N): In Python 2, the range() function returns a list, meaning it has a time complexity of O(N), where N is the length of the range. The range() function returns the entire list to perform any operations, including member checks.

Space Complexity

  • O(1): The space complexity of the range() function in Python should be O(1) because it only creates an immutable sequence object representing a range of values. 
     
  • O(N): In Python 2, the range() function returns a list, and then space complexity should be O(N) because it yields a mutable and variable-length object. 

Also see, Python Filter Function

Generate a sequence of numbers with a specific step size

While using range () in Python, you can specify the beginning, terminate, and increment arguments for generating a sequence of numbers with a specific step size. You can adjust the arguments according to your needs. You can generate different sequences with different step sizes according to your requirement in the code. 

Note: The increment parameter should be a non-zero integer. Otherwise, you'll get a ValueError.

CODE

# Generating a series of numbers from 0 to 10 with increments of 2.
for i in range(0, 10, 2):
    
    # Print the values.
    print(i)

OUTPUT

output 1


EXPLANATION

exp 1

We are using the for loop to iterate over this series of numbers. "i" is set to 0 and printed when the loop starts. Then, the range() function will increment the value of "i" by two and generate the following number in the series, which is 2. This process will continue until the series reaches (but does not include) 10. At 10, this loop exits. 

Generate a sequence of numbers in reverse order

Here, the increment value will be -1. It means the numbers in the sequence will decrease by 1 with each loop iteration. 

CODE

# Now we are generating a sequence of numbers in reverse order with increment value -1.
for i in range(10, 0, -1):
    
    # Printing the value of i. 
    print(i)

OUTPUT

output 2

EXPLANATION

exp 2

We start at 10 and end at 1 (excluding 0), with a step value of -1.

The range() function decrements the value of "i" by 1 to generate the following number in the sequence. The loop will continue until it reaches (but does not include) the second range parameter 0.

Iterate through the indices of a list

You can also use the range() function in Python to go through the indices of a list.  The loop you will run iterates through indices and prints the output.

CODE

#Firstly, we are defining coding languages.
coding_languages = ['C++', 'Java', 'Python', 'C']

# Printing the message with index i plus 1.
for i in range(len(coding_languages)):
    print("Ninja", i+1, "can code in", coding_languages[i])

OUTPUT

output 3

EXPLANATION

exp 3

In this example, we use a for loop with the range() function to go through the indices of the list.

For every index i, we print a message. Since Python lists are zero-indexed, we are adding 1 to i. Finally, we are string concatenating to print the output.

Concatenate two ranges

Firstly you can create two different range() objects. Now use the range() function in Python. Finally, you can combine them using the chain() function from the itertools module. 

chain() function takes two or more iterables. It will return a single iterator that goes through all the items in each iterable in order.

CODE

from itertools import chain

#Creating the two ranges.
range1 = range(5)
range2 = range(25, 35)
concatenated_range = chain(range1, range2)

# Print the concatenated range.
print([i for i in concatenated_range])

OUTPUT

output 4

EXPLANATION

exp 4

 

Define range1, which has the integers from 0 to 4 (inclusive). Then define the range2 with integers from 25 to 34 (inclusive). Then use the chain() function to concatenate the two ranges. The output will be a series of integers from 0 to 4 followed by integers from 25 to 34.

Get the tech career you deserve, faster!
Connect with our expert counsellors to understand how to hack your way to success
User rating 4.7/5
1:1 doubt support
95% placement record
Akash Pal
Senior Software Engineer
326% Hike After Job Bootcamp
Himanshu Gusain
Programmer Analyst
32 LPA After Job Bootcamp
After Job
Bootcamp

Xrange in Python

While using Python 3 you will not find xrange(). It is removed from Python 3. Generally, it gives output that generates integers on the fly. It is very time-saving for creating a series. In Python 3, the range() function performs the same task as xrange() in Python 2. The only difference is range() returns a list in place of a sequence object. You can use it to generate more minor sequences better than the range() function. You can use it to create infinite sequences of integers in combination with other functions (chain(), count(), tee(), islice() etc) present in Python.

Syntax

xrange([beginning], terminate[, increment])

Parameters

  • beginning (optional): It is the first number of your series. Suppose you will not provide it. The compiler will use 0 as the default.
     
  • terminate (must): It is the last number of your series (the series is exclusive of this number)
     
  • increment (optional): The increment between each number in the series. If you do not provide it, the compiler will set the default value as 1.
xrange exp

Return Type

The return type is a sequence generator that returns integers one at a time. You can also use it for loops and other operations according to your need.

Time Complexity

  • O(n): if you are using it in for loop to go through a series. n is the number of values in your series. 
     
  • O(1): The time complexity can be O(1) for getting the next value in the series. xrange() outputs the sequence on-the-fly as you pass through it. It does not need to pre-compute the entire series. 

Space Complexity 

O(1): As it stores the beginning, terminate, and increment values only.

For loops using xrange()

You can use it for loops where you must pass through a range of integers. Remember to use it where your list is not required to be created in memory.

CODE

# This loop will be executed four times.
for i in xrange(4):
    # Printing the values.
    print i

OUTPUT

output 5

EXPLANATION

exp 5

We are printing the values beginning from 0. It increments by 1 to 3 (since xrange(4) outputs series from 0 to 3, which is one less than the terminate parameter).

Summation using xrange()

You can use it for summation operations when you want a range of integers without requiring a list to be created in memory.

CODE

# Initalise total_sum with zero.
total_sum = 0
# Using for loop to go through integers created by xrange.
for i in xrange(1, 11):
    
    # Adding values.
    total_sum += i  
print total_sum

OUTPUT

output 6

EXPLANATION

exp 6

 

We are calculating the sum of the integers from 1 to 10 (inclusive) using a for loop and the xrange(). We are adding the current integer in total_sum with each iteration. 

Indexing using xrange()

When creating a new list in memory is unnecessary, xrange() is very useful. You can use it to review a list's index values or an array.

CODE

# List of some programming languages.
programming_lang = ['C++', 'Java', 'Swift', 'HTML']

 # We are using a for loop to pass over the indices and len is for getting length of list.
for i in xrange(len(programming_lang)):
    print programming_lang[i]

OUTPUT

output 7

EXPLANATION

exp 7

In each iteration of the loop, we use the current index i to get the corresponding element of the list using square brackets ([]). 

Also see, Difference Between Structure and Union

Difference Table range vs xrange in Python

Here is a table summarizing range vs xrange in Python:

range()xrange()
It returns a list.It returns an xrange object.
The items generated are stored in memory.It generates items on the fly. It can be faster and memory efficient for large ranges.
It takes more time to create the list of numbers. It is not a generator.It generates numbers only when required. It is a generator.
The output can be sliced and diced.The output cannot be sliced or diced.
It is beneficial to create a list of a specified length.It cannot create a list of a specified length.
It is used more frequently. It is easier to use and understand.You must pass it to only some built-in functions, which expect a list.
You can apply it when the list can fit in memory.

It is beneficial when the list is too large to be held in memory.

 

It is present in both Python 2 and Python 3.It is removed from Python 3. It is only present in Python 2.

 

Must Read Python List Operations

Check out Escape Sequence in Python

Frequently Asked Questions

How do range() and enumerate() differ?

The range() function will give a sequence of integer numbers. The enumerate() will give pairs of the form (index, value) for each element in an iterable. In case of looping over a sequence and you want both the value and index, you prefer using enumerate().
 

What will happen if you pass a negative value to range()?

If you try passing a negative value to range(), it will give an empty sequence. The range() function generates numbers in increasing order by default. When we pass in a negative value, no numbers will be left to create in increasing order. 
 

What happens if you will pass a non-integer value to range()?

You will get a TypeError. A message saying that range() requires an integer as input will be displayed on your screen. This is because range() gives a sequence of numbers and needs integers to determine the series' beginning, terminate, and increment parameters.
 

Will you use xrange() in a list comprehension?

Yes, you can use xrange() in a list comprehension in Python 2. It gives an ordered series of integers. Now in Python 3, the range() function acts like xrange(), so there is no need left for xrange().
 

How will you specify a custom step value for range()?

You have to pass a third parameter to the function, which specifies the step size between each value in the sequence. It is optional. Its default value is one if you are not specifying. While passing a negative step value, remember the starting value should be greater than the ending value.

Conclusion

This article thoroughly covered the range() vs xrange() in Python. We individually discussed both functions, including their syntax, parameters, and how to use them in various cases. This article also has many code examples for different cases to make learning concepts easier. Reading these articles will help you understand the concepts in a better way related to Python.

Refer to our guided paths on Coding Ninjas Studio to learn more about DSA, Competitive Programming, JavaScript, System Design, etc. Enrol in our courses, refer to the mock test, and problems look at the interview experiences and interview bundle for placement preparations.

Happy Coding!

 

 

Previous article
Global Keyword in Python
Next article
Recursion in Python
Guided path
Free
gridgp-icon
Basics of python
7 chapters
127+ Problems
gp-badge
Earn badges and level up
Live masterclass