[Python-Dev] re: for in dict (user expectation poll)
Ka-Ping Yee
ping@lfw.org
Mon, 5 Feb 2001 11:26:53 -0800 (PST)
On Mon, 5 Feb 2001, Greg Wilson wrote:
> OK, now here's the hard one. Clearly,
>
> (a) for i in someList:
>
> has to continue to mean "iterate over the values". We've agreed
> that:
>
> (b) for k:v in someDict:
>
> means "iterate through the items". (a) looks like a special case
> of (b). I therefore asked my colleagues to guess what:
>
> (c) for x in someDict:
>
> did. They all said, "Iterates through the _values_ in the dict",
> by analogy with (a).
>
> I then asked, "How do you iterate through the keys in a dict, or
> the indices in a list?" They guessed:
>
> (d) for x: in someContainer:
>
> (note the colon trailing the iterator variable name). I think that
> the combination of (a) and (b) implies (c), which leads in turn to
> (d). Is this what we want? I gotta say, when I start thinking about
> how many problems my students are going to bring me when accidentally
> adding or removing a colon in the middle of a 'for' statement changes
> the iteration space from keys to values, and I start feeling queasy...
The PEP explicitly proposes that (c) be an error, because i
anticipated and specifically wanted to avoid this ambiguity.
Have you had a good look at it?
I think your survey shows that the PEP made the right choices.
That is, it supports the position that if 'for key:value' is
supported, then 'for key:' and 'for :value' should be supported,
but 'for x in dict:' should not. It also shows that 'for index:'
should be supported on sequences, which the PEP suggests.
-- ?!ng