Python: Unpacking an inner nested tuple/list while still getting its index number

11,237
for i, (letter, word) in enumerate(seq_nested):
  print i, letter, word
Share:
11,237
Kit
Author by

Kit

Updated on June 06, 2022

Comments

  • Kit
    Kit almost 2 years

    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?

  • michaelsnowden
    michaelsnowden over 7 years
    @MadPhysicist Yes