Why Is the Output of My Range Function Not a List?
That's because range
and other functional-style methods, such as map
, reduce
, and filter
, return iterators in Python 3. In Python 2 they returned lists.
What’s New In Python 3.0:
range()
now behaves likexrange()
used to behave, except it works with values of arbitrary size. The latter no longer exists.
To convert an iterator to a list you can use the list
function:
>>> list(range(5)) #you can use list()
[0, 1, 2, 3, 4]
Usually you do not need to materialize a range into an actual list but just want to iterate over it. So especially for larger ranges using an iterator saves memory.
For this reason range()
in Python 3 returns an iterator instead (as xrange()
did in Python 2). Use list(range(..))
if you want an actual list instead for some reason.