Enumerate 정의하기

Enumerate() in Python

Enumerate() method adds a counter to an iterable and returns it in a form of enumerate object. This enumerate object can then be used directly in for loops or be converted into a list of tuples using list() method.

사용해보기

avengers = ['hawkeye', 'ironman', 'thor', 'captain america']
e = enumerate(avengers)
print(type(e)) # <class 'enumerate'>

e_list = list(e)
print(e_list)
[(0,'hawkeye'),(1,'ironman'),(2,'thor'),(3,'captain america')]

Don’t write this vs. Write this

# Don't write this
my_container = ['Jason','Mike','Tim']
index = 0
for element in my_container:
    print('{} {}'.format(index, element))
    index++

# Write this
for index, element in enumerate(my_container):
    print('{} {}'.format(index, element))