enumerate() question
Leif K-Brooks
eurleif at ecritters.biz
Mon May 22 10:39:49 EDT 2006
Gregory Petrosyan wrote:
> Hello!
> I have a question for the developer[s] of enumerate(). Consider the
> following code:
>
> for x,y in coords(dots):
> print x, y
>
> When I want to iterate over enumerated sequence I expect this to work:
>
> for i,x,y in enumerate(coords(dots)):
> print i, x, y
>
> Unfortunately, it doesn't =( and I should use (IMHO) ugly
>
> for i,pair in enumerate(coords(dots)):
> print i, pair[0], pair[1]
Use:
for i, (x, y) in enumerate(coords(dots)):
print i, x, y
> So, why enumerate() works this way and is there any chance of changing
> the behaviour?
Because enumerate has no way to distinguish between iterables you do and
don't want unpacked. So, for example, this wouldn't work under your
proposal:
for index, string in ["foo", "bar", "baz"]:
print "String number %s is %s." % (index, string)
But this would:
for index, x, y, z in ["foo", "bar", "baz"]:
print "First character of string number %s is %s." % (index, x)
More information about the Python-list
mailing list