Python: interpreter returns objects / functions instead of evaluation

I am using python-3.2.3 64bit and see weird behavior.

Example using the interpreter: Input

>>> range(10) 

leads to the conclusion

 range(0, 10) 

when should he print

 [0, 1, 2, 3, 4, 5, 6, 7, 8, 9] 

Symmetric input

 >>> l = range(10) >>> f = filter( lambda x: x<2, l) >>> f 

leads to exit

 <filter object at 0x00000000033481D0> 

but it should be

 [0, 1] 

Obviously, I can not do anything with this object:

 >>>> len(f) Traceback (most recent call last): File "<pyshell#5>", line 1, in <module> len(f) TypeError: object of type 'filter' has no len() 

What is wrong here?

+4
source share
2 answers

There is nothing bad. range() - this Py3.x gives elements 1 at the same time as generators, unlike its behavior in Py2.x, which was supposed to generate a list on the right, and then immediately return it to you. End your range(10) call with list() and you get what you expect.

+18
source

These functions return iterator objects. You can convert them to lists using list(range(0, 10)) or list(f) . You can also iterate over the results, for example:

 for i in range(0, 10): print(i) 

Finally, you can use the next function to get the following element:

 l = range(0, 10) l1 = next(l) l2 = next(l) 

Returning iterators instead of lists allow you to perform complex operations on elements without loading them all into memory. For example, you can iterate over a huge file and convert it by character, without loading the entire file into memory.

+3
source

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


All Articles