while (a=b()) ...

Jim Meier fatjim at home.com
Sun May 16 23:24:05 EDT 1999


Tim Peters wrote:

> [Jim Meier]
> > ...
> > Aha! I see now... the * is intended to be the guarauneed-sequential
> > number of the current iteration, then?
>
> "for x in thing:" follows a protocol that's *defined* to call
> thing.__getitem__ first with 0, then with 1, and so on.  That's how you can
> write a class of your own whose instances participate in "for".  The 0, 1,
> 2, ... sequence is thus not arbitrary, but something the language
> guarantees.
>
> > I sympathise with the yearning, but my dislike is increased by the (to
> > me, anyways) non-intuitive feel of it.
>
> The sequence 0, 1, 2, ..., or the asterisk?

The asterisk. (I used to have arguments, though, back in high school, with my
math teachers, who always insisted that sequence numbering should start at
"1"... :)

>
> > Does  anyone use (untested):
> > #defined somewhere global
> > def iterate(seq):
> >     return apply(lambda x,y: (seq(x), x), range(len(seq)))
> >
> > #where you need to iterate with index
> > for (index,item) in iterate(sequence):
> >     print "item %i: %s" % (index, sequence)
> >
> > ?
>
> No, although it was suggested in each of the last 10 incarnations of this
> thread too <wink>.  The usual spelling exploits a supernaturally fast
> endcase of map:
>
> def iterate(seq):
>     return map(None, range(len(seq)), seq)

Please excuse my incredibly poor functional programming. I've never been able to
think quite straight using "map" and "apply", and other lisp-isms.

> > ...
> > However, my main, big, current interest in Python is it's readability
> > and easy teachability to new users who have never programmed before.
> > I'm trying to make programming a nearly integral part of using my
> > project (a simulation-style game). So I'm looking for the most immediately
> > readable solutions, so that the skittish-but-ready aren't scared off.
>
> Will a simulation-style game have situations that require iterating over a
> sequence terminated by a reserved sentinel value?  I don't think it's
> coincidence that this thread always begins with reading lines from a huge
> file.
>
> then-again-it's-no-coincidence-that-my-toe-itches-either-ly y'rs  - tim

They'll be able to use the language for _anything_, including generating reports
which filter or enhance sets of data. So the parallel is there - the dataset is
just smaller.

-Jim





More information about the Python-list mailing list