range () — returns a list of numbers created with the range () function.
xrange () — this function returns a generator object which can be used to display numbers only by looping. When requested, only a specific range is displayed, and therefore it is called “ deferred .
Both are implemented differently and have different characteristics associated with them. Comparison points:
- Return type
- Operation Usage
range () returns — list as a return type.
xrange () returns — object xrange () .
The return type of range () is: The return type of xrange () is:
A variable storing a range created by range () takes more memory compared to a variable storing a range using xrange (). The main reason for this is the return type of range () — list, and xrange () — the xrange () object.
The size allotted using range () is: 80064 The size allotted using xrange () is: 40
Since range () returns a list, all operations that can be applied to a list can be used with it. On the other hand, since xrange () returns an xrange object, list-related operations cannot be applied to them, which is a drawback.
Traceback (most recent call last): File "1f2d94c59aea6aed795b05a19e44474d.py", line 18, in print (x [2: 5]) TypeError: sequence index must be integer, not ’slice’
The list after slicing using range is: [3, 4, 5] The list after slicing using xrange is:
Due to the fact that xrange () only evaluates a generator object containing only the values required for lazy evaluation, therefore is faster in implementation than range ().
- If you want to write code that works in both Python 2 and Python 3, use range () as xrange is deprecated in Python 3
- range () is faster if you repeat the same sequence multiple times.
- xrange () should restore each time an integer object, but range () will have real integer objects. (This will always work worse in terms of memory, however)
This article is provided by Manjit Singh . If you are as Python.Engineering and would like to contribute, you can also write an article using contribute.python.engineering or by posting an article contribute @ python.engineering. See my article appearing on the Python.Engineering homepage and help other geeks.
Please post comments if you find anything wrong or if you would like to share more information on the topic discussed above.