Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why Is the Output of My Range Function Not a List?

According to the Python documentation, when I do range(0, 10) the output of this function is a list from 0 to 9 i.e. [0, 1, 2, 3, 4, 5, 6, 7, 8, 9]. However the Python installation on my PC is not outputting this, despite many examples of this working online.

Here is my test code...

test_range_function = range(0, 10)
print(test_range_function)
print(type(test_range_function))

The output of this I'm thinking should be the list printed, and the type function should output it as a list. Instead I'm getting the following output...

c:\Programming>python range.py
range(0, 10)
<class 'range'>

I haven't seen this in any of the examples online and would really appreciate some light being shed on this.

like image 709
FiveAlive Avatar asked May 17 '13 22:05

FiveAlive


2 Answers

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 like xrange() 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]
like image 59
Ashwini Chaudhary Avatar answered Nov 15 '22 09:11

Ashwini Chaudhary


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.

like image 41
ThiefMaster Avatar answered Nov 15 '22 09:11

ThiefMaster