Both my professor and this guy claim that range
creates a list of values.
"Note: The range function simply returns a list containing the numbers from x to y-1. For example, range(5, 10) returns the list [5, 6, 7, 8, 9]."
I believe this is to be inaccurate because:
type(range(5, 10))
<class 'range'>
Furthermore, the only apparent way to access the integers created by range
is to iterate through them, which leads me to believe that labeling range
as a lists is incorrect.
It depends.
In python-2.x,
range
actually creates a list (which is also a sequence) whereasxrange
creates anxrange
object that can be used to iterate through the values.On the other hand, in python-3.x,
range
creates an iterable (or more specifically, a sequence)range creates a list if the python version used is 2.x . In this scenario range is to be used only if its referenced more than once otherwise use xrange which creates a generator there by redusing the memory usage and sometimes time as it has lazy approach.
xrange is not there in python 3.x rather range stands for what xrange is for python 2.x
refer to question What is the difference between range and xrange functions in Python 2.X?
In Python 2.x,
range
returns a list, but in Python 3.xrange
returns an immutable sequence, of typerange
.Python 2.x:
Python 3.x:
In Python 2.x, if you want to get an iterable object, like in Python 3.x, you can use
xrange
function, which returns an immutable sequence of typexrange
.Advantage of
xrange
overrange
in Python 2.x:Note:
Nope. Since
range
objects in Python 3 are immutable sequences, they support indexing as well. Quoting from therange
function documentation,For example,
All these are possible with that immutable
range
sequence.Recently, I faced a problem and I think it would be appropriate to include here. Consider this Python 3.x code
One would expect this code to print every ten numbers as a list, till 99. But, it would run infinitely. Can you reason why?
Solution