Rectangle 27 0

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


>>> list(range(5)) #you can use list()
[0, 1, 2, 3, 4]

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.

To convert an iterator to a list you can use the list function:

range() now behaves like xrange() used to behave, except it works with values of arbitrary size. The latter no longer exists.

Note
Rectangle 27 0

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


>>> list(range(5)) #you can use list()
[0, 1, 2, 3, 4]

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.

To convert an iterator to a list you can use the list function:

range() now behaves like xrange() used to behave, except it works with values of arbitrary size. The latter no longer exists.

Note
Rectangle 27 0

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


and it also implements an O(1) __contains__. so when novices write 5 in range(1, 21, 2) (as they always have), it's no longer a mistake, but instance good and perfectly idiomatic code.

+1, This explains the reason for the change and why it's better. One small, subtle distinction - range() in 3.x returns an iterable, not an iterator. It has some advantages over a straight up iterator, like it's not exhausted when it's looped over, and it's a sequence, so you can slice it, etc... range(10)[:5] == range(0, 5).

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.

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.

Note