Is current integer for-loop syntax a wart?
phil hunt
philh at comuno.freeserve.co.uk
Sat Mar 9 08:05:56 EST 2002
On Sat, 9 Mar 2002 00:29:02 +0000 (UTC), Huaiyu Zhu <huaiyu at gauss.almadan.ibm.com> wrote:
>- Not a wart:
>
> 1. It is very clear what it does.
> 2. range() can be used elsewhere. No new syntaxes.
> 3. In most situations you loop over list of items instead of counters.
>
>
>- Wart:
>
> When you do need the index, neither of the following is very nice looking:
>
> for i, x in zip(range(len(a)), a):
> b[i] = x
>
> for i in range(len(a)):
> b[i] = a[i]
What you sohuld be able to do is say:
for i in a.keys():
b[i] = a[i]
You can get a dictionary's keys, so you ought to be able to do so
with sequence types, in the same way.
(Actually I'd say it is a failing in Python generally that the
collection typers are not as well-integrated-together as in e.g.
Smalltalk).
>the solution is too broad: it produces iterators in many uninteded places.
>
>
>Two ideas that I do like:
>
> for i, x in items(a):
> b[i] = x
That's nice.
> for i in indices(a):
> b[i] = a[i]
Instead of indices(a) use a.keys() for consistency with mapping
types. This could return an xrange.
>They address the right problems at minimum cost. They can be extended to
>xitems and xindici, of course.
Indeed.
--
<"><"><"> Philip Hunt <philh at comuno.freeserve.co.uk> <"><"><">
"I would guess that he really believes whatever is politically
advantageous for him to believe."
-- Alison Brooks, referring to Michael
Portillo, on soc.history.what-if
More information about the Python-list
mailing list