Why is the output of my range function not a list?

According to the Python documentation, when I do a range of (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, installing Python on my PC does not display this, despite many examples of this work on the Internet.

Here is my test code ...

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

The result of this, which I think of, should be printed in a list, and the type function should output it as a list. Instead, I get the following output ...

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

I have not seen this in any of the examples on the Internet, and I would really appreciate that this light failed.

+4
source share
2 answers

This is because range and other functional-style methods, such as map , reduce and filter , return iterators in Python 3. In Python 2, they return lists.

What's New in Python 3.0 :

range() now behaves like xrange() used for maintenance, except that it works with an arbitrary size value. 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] 
+12
source

Usually you do not need to enter a range in the actual list, but just need to iterate over it. Therefore, especially for large ranges using an iterator, memory is saved.

For this reason, range() in Python 3 instead returns an iterator (as xrange() in Python 2). Use list(range(..)) if for some reason you need an actual list.

+5
source

Source: https://habr.com/ru/post/1481475/


All Articles