5

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?

2 Answers2

14

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.

idjaw
  • 25,487
  • 7
  • 64
  • 83
  • While this was my first attempt as well and works for lists, it won't work for any `iterable`, i.e. it won't work on the ones that are not `subscriptable`. On the other hand, the answer by @awesoon actually works for any `iterable`. – penelope May 21 '19 at 11:23
10

You could use itertools.islice in order to take a slice of an iterable:

In [9]: from itertools import islice

In [10]: list(islice(enumerate(seasons), 2, None))
Out[10]: [(2, 'fall'), (3, 'winter')]
awesoon
  • 32,469
  • 11
  • 74
  • 99
  • 2
    This, thank you. Your solution works for any `iterable` - and I'm honestly surprised this question/answer isn't getting more attention. – penelope May 21 '19 at 11:24