views:

134

answers:

1

I am familiar with using enumerate():

>>> seq_flat = ('A', 'B', 'C')
>>> for num, entry in enumerate(seq_flat):
        print num, entry
0 A
1 B
2 C

I want to be able to do the same for a nested list:

>>> seq_nested = (('A', 'Apple'), ('B', 'Boat'), ('C', 'Cat'))

I can unpack it with:

>>> for letter, word in seq_nested:
        print letter, word
A Apple
B Boat
C Cat

How should I unpack it to get the following?

0 A Apple
1 B Boat
2 C Cat

The only way I know is to use a counter/incrementor, which is un-Pythonic as far as I know. Is there a more elegant way to do it?

+10  A: 
for i, (letter, word) in enumerate(seq_nested):
  print i, letter, word
Alex Martelli