Iteratoration question
grocery_stocker
cdalten at gmail.com
Thu Apr 2 22:19:07 EDT 2009
On Apr 2, 6:33 pm, "Rhodri James" <rho... at wildebst.demon.co.uk> wrote:
> On Fri, 03 Apr 2009 02:07:38 +0100, grocery_stocker <cdal... at gmail.com>
> wrote:
>
> > Okay, I was thinking more about this. I think this is also what is
> > irking me. Say I have the following..
>
> >>>> a = [1,2,3,4]
> >>>> for x in a:
> > ... print x
> > ...
> > 1
> > 2
> > 3
> > 4
>
> > Would 'a' somehow call __iter__ and next()? If so, does python just
> > perform this magically?
>
> No. It's "for" that invokes the iteration protocol; that's pretty
> much the definition of it. You have read the iteration protocol
> after it's been mentioned so many times now, haven't you?
>
> "for" calls iter(a), which in turn calls a.__iter__(), to get an
> iterator. Once it's got, "for" calls next() on the iterator each
> time round the loop. Very approximately, that little for-loop
> translates to:
>
> a = [1,2,3,4]
> i = iter(a)
> try:
> while True:
> x = i.next()
> print x
> except StopIteration:
> pass
>
Okay, at the risk of sounding like a total slacker, I've only briefly
scanned over the iteration protocol. After I get up in the morning,
I'll probably read it more closely.
More information about the Python-list
mailing list