Search code examples
pythonenumerate

Python: Enumeration


People have said that the enumerate function is a hidden trick in python. I am still unsure as to what it does. The documentation just tells me that it returns an enumerate object. That doesn't exactly help me in understanding this concept.

What does enumeration do?


Solution

  • enumerate() can be used with any iterable. It enumerates the values returned by the iterable.

    3>> enumerate(['a', 'b', 'c'])
    <enumerate object at 0x7f1340c44a50>
    3>> list(enumerate(['a', 'b', 'c']))
    [(0, 'a'), (1, 'b'), (2, 'c')]
    3>> list(enumerate({'a', 'b', 'c'}))
    [(0, 'c'), (1, 'b'), (2, 'a')]
    3>> list(enumerate({'a':0, 'b':0, 'c':0}))
    [(0, 'c'), (1, 'b'), (2, 'a')]
    

    Note that the set and dict results are not in error; they are arbitrarily ordered, hence do not necessarily "come out" the same way they "go in". And as always, iterating over a mapping yields its keys.