Search code examples
pythonenumerate

skip first two elements in an enumeration -- python


This is not what I want from enumerate:

>>> seasons = ['Spring', 'summer', 'fall', 'winter']

>>> list(enumerate(seasons, start =2))

[(2, 'Spring'), (3, 'summer'), (4, 'fall'), (5, 'winter')]

This IS the functionality I want from enumerate:

 >>> list(enumerate(seasons, start =2))
[(2, 'fall'), (3, 'winter')]

See the difference? The first one just says, "fine I'll call your 0th element 2 if you really want me to"

The second one says, "I understand that you just want to begin the loop at the second index, much like range(2, len(seasons)) would do"

Is there no way to do this simply with enumerate?


Solution

  • Why not just slice the first two elements?

    print(list(enumerate(seasons[2:], start=2)))
    

    Output:

    [(2, 'fall'), (3, 'winter')]
    

    To understand what is going on with enumerate and the start. Try iterating over it to see what it outputs:

    for i, v in enumerate(seasons, start=2):
        print(i, v)
    

    As you can see your i, which simply increments along iterating through your seasons list is what starts at 2. But each value in the list is actually from the start of your list. This just further proves that start does not have anything to do with the actual starting point of your list iteration.