Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Python: Interpreter returns Objects/Functions instead of evaluating

Tags:

python

I am using python-3.2.3 64bit and I am seeing some strange behavior.

For Example when using the interpreter: The Input

>>> range(10)

results in the Output

range(0, 10)

when it should print

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

Simmilary Input

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

leads to Output

<filter object at 0x00000000033481D0>

but it should be

[0, 1]

Obviously I cant do anything with that 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()

Whats wrong here?

like image 342
Max Tet Avatar asked Nov 29 '22 14:11

Max Tet


2 Answers

Nothing is wrong. range() is Py3.x yields items 1 at a time like generators unlike its behaviour in Py2.x that was to generate a list right then and there and then return it to you. Wrap your call to range(10) in a call to list() and you'll get what you expect.

like image 55
Christian Witts Avatar answered May 15 '23 00:05

Christian Witts


Those functions return iterator objects. You can convert them to lists using list(range(0, 10)) or list(f). You also can iterate through the results like:

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

Finally, you can use next function to get next item:

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

Returning iterators instead of lists allow to perform complex operations on items without having to load all of them into memory. For example, you could iterate through a huge file and convert it character by character, without needing to load the entire file into memory.

like image 44
Charles Brunet Avatar answered May 15 '23 00:05

Charles Brunet