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?
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
EXPLANATION
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
EXPLANATION
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
EXPLANATION
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
EXPLANATION
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.