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?
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.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With