DEV Community

Cover image for Beginner Python tips Day - 01 Enumerate
Paurakh Sharma Humagain
Paurakh Sharma Humagain

Posted on

Beginner Python tips Day - 01 Enumerate

# Day 01 - Enumerate
# Provides counter that matches
# the number of items in the list

my_list = ['hello', 'world', '!']

# Without enumerate
for index in range(len(my_list)):
    print(index, my_list[index])
'''
Prints
0 hello
1 world
2 !
'''

# With enumerate
for counter, value in enumerate(my_list):
    print(counter, value)
'''
Prints
0 hello
1 world
2 !
'''

# Don't confuse it with index
# because, the counter can start from any integer
for counter, value in enumerate(my_list, 2):
    print(counter, value)
'''
Prints
2 hello
3 world
4 !
'''

Top comments (0)