Wednesday, June 11, 2008

Python: Iterators

Guido said: "The use of iterators pervades and unifies Python. Behind the scenes, the for statement calls iter() on the container object". But it gets better! Generators make it easy to create iterators. They use yield which calls next() behind the scenes and resumes where it left-off. Then "simple generators can be coded succinctly as expressions": So here's a loop (which is already using an iterator behind the scenes):
>>> for i in range(10):  
...     print i,
... 
0 1 2 3 4 5 6 7 8 9
>>> 
Which I'll use to define a list:
>>> [i for i in range(10)]
[0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
>>>
Or make a generator object:
>>> (i for i in range(10))
<generator object at 0x7f5fdb38d518>
>>>
Which I can feed to a function:
>>> sum(i for i in range(10))
45
>>> 
Makes Python feel more Functional.

No comments: