Search code examples
pythonenumerate

Different ways of using enumerate


I know the basic way that enumerate works, but what difference does it make when you have two variables in the for loop? I used count and i in the examples below

This code:

Letters = ['a', 'b', 'c']
for count, i in enumerate(Letters):
    print(count, i)

and this:

Letters = ['a', 'b', 'c']
for i in enumerate(Letters):
    print(i)

Both give the same output, this:

>>>
    0 'a'
    1 'b'
    2 'c'

Is writing code in the style of the first example beneficial in any circumstances? What is the difference? If you know any other ways that could be useful, just let me know, I am trying to expand my knowledge within python


Solution

  • In the first example, count is set to the index, and i is set to the element.

    In the second example, i is being set to the 2-element tuple (index, element).

    The first example is equivalent to:

    count, i = 0, 'a'
    

    which is the same as:

    count = 0
    i = 'a'
    

    And the second example is the same as:

    i = (0, 'a')