enumerate() question

Diez B. Roggisch deets at nospam.web.de
Mon May 22 16:36:50 CEST 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]
> So, why enumerate() works this way and is there any chance of changing
> the behaviour?

It works that way because enumerate returns a tuple - index, value. And it
doesn't care what is inside value. Actually, it can't - how would you then
write something like this?

l = [1, ('a', 'tuple'), 3]

for i, value in enumerate(l):
    print i, value

But your problem can be solved in an elegant fashion anyway. When *you* know
the structure of the values (and who else does?), you can simply use nested
sequence unpacking:

for i, (x, y) in enumerate(coords):



More information about the Python-list mailing list