I recently started learning python 3.
In python 2 range()
function can be used to assign list elements.
>>> A = []
>>> A = range(0,6)
>>> print A
[0, 1, 2, 3, 4, 5]
where as in python 3 when range()
function is used this is happening
>>> A = []
>>> A = range(0,6)
>>> print(A)
range(0, 6)
why is this happening?
why did python do this change?
Is it a boon or a bane ?
Python 3 uses iterators for a lot of things where python 2 used lists.The docs give a detailed explanation including the change to
range
.The advantage is that Python 3 doesn't need to allocate the memory if you're using a large range iterator or mapping. For example
requires a lot less memory in python 3. If you do happen to want Python to expand out the list all at once you can
In python3, do
You will get the same result.
in python 2,
range
is a built-in function. below is from the official python docs. it returns a list.also you may check
xrange
only existing in python 2. it returnsxrange
object, mainly for fast iteration.by the way, python 3 merges these two into one
range
data type, working in a similar way ofxrange
in python 2. check the docs.Python 3
range()
function is equivalent to python 2xrange()
function notrange()
Explanation
In python 3 most function return Iterable objects not lists as in python 2 in order to save memory. Some of those are
zip()
filter()
map()
including .keys .values .items()
dictionary methods But iterable objects are not efficient if your trying to iterate several times so you can still uselist()
method to convert them to lists