[Python-Dev] Single- vs. Multi-pass iterability

Delaney, Timothy tdelaney@avaya.com
Mon, 22 Jul 2002 09:23:55 +1000


> From: Ka-Ping Yee [mailto:ping@zesty.ca]
> 
> It's just not the way i expect for-loops to work.  Perhaps we would
> need to survey people for objective data, but i feel that most people
> would be surprised if
> 
>     for x in y: print x
>     for x in y: print x
> 
> did not print the same thing twice, or if
> 
>     if x in y: print 'got it'
>     if x in y: print 'got it'
> 
> did not do the same thing twice.  I realize this is my own opinion,
> but it's a fairly strong impression i have.
> 
> Well, for a generator, there is no underlying sequence.
> 
>     while 1: print next(gen)
> 
> makes it clear that there is no sequence, but
> 
>     for x in gen: print x
> 
> seems to give me the impression that there is.

I think this is the crux of the matter. You see for: loops as inherently
non-destructive - that they operate on containers. I (and presumably Guido,
though I would never presume to channel him ;) see for: loops as inherently
destructive - that they operate on iterators. That they obtain an iterator
from a container (if possible) is a useful convenience.

Perhaps the terminology is confusing. Consider a queue.

for each person in the queue:
    service the person

Is there anyone who would *not* consider this to be destructive (of the
queue)?

Tim Delaney