[Tutor] iterators

Keith Winston keithwins at gmail.com
Sat Jan 18 09:51:56 CET 2014


I don't really get iterators. I saw an interesting example on
Stackoverflow, something like

with open('workfile', 'r') as f:
    for a, b, c in zip(f, f, f):
....

And this iterated through a, b, c assigned to 3 consecutive lines of
the file as it iterates through the file. I can sort of pretend that
makes sense, but then I realize that other things that I thought were
iterators aren't (lists and the range function)... I finally succeeded
in mocking this up with a generator:

gen = (i for i in range(20))
for t1, t2, t3 in zip(gen, gen, gen):
    print(t1, t2, t3)

So I'm a little more confident of this... though I guess there's some
subtlety of how zip works there that's sort of interesting. Anyway,
the real question is, where (why?) else do I encounter iterators,
since my two favorite examples, aren't... and why aren't they, if I
can iterate over them (can't I? Isn't that what I'm doing with "for
item in list" or "for index in range(10)")?

-- 
Keith


More information about the Tutor mailing list