Search code examples
pythonlistpython-3.xindexofenumerate

enumerating list already of type list


I was wondering if some kind soul could explain why I have to convert a list that is already of type list before calling enumerate on it.

>>> l = ['russell', 'bird', 'thomas']
>>> print(type(l))
Type is: `class 'list'`.

If I enumerate over this list without explicitly declaring it as such, this is the output:

>>> print(enumerate(l))
enumerate object at 0x00B1A0F8

When explicitly declaring this list as a list, the output is as expected:

>>> print(list(enumerate(l)))
[(0, 'russell'), (1, 'bird'), (2, 'thomas')]

If someone could help explain why this is the case, it'd be greatly appreciated.


Solution

  • You have two different objects here. Let's say you define a function:

    def my_func(my_list):
        return 4
    

    If you did my_func(l), of course it wouldn't return a list. Well, enumerate() is the same way. It returns an enumerate object, not a list. That object is iterable, however, so it can be converted to a list. For example:

    def my_enumerate(my_list):
        index = 0
        for item in my_list:
            yield index, item
            index += 1
    

    That is pretty much how enumerate works. Our function is a generator function and returns a generator object. Since generators are iterable, you can convert it to a list:

    print(list(my_enumerate(l))