43

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?

Zero Piraeus
  • 52,181
  • 26
  • 146
  • 158
Kit
  • 28,485
  • 35
  • 99
  • 148

1 Answers1

83
for i, (letter, word) in enumerate(seq_nested):
  print i, letter, word
Alex Martelli
  • 811,175
  • 162
  • 1,198
  • 1,373