Beginner Python tips Day - 01 Enumerate

paurakhsharma

Paurakh Sharma Humagain

Posted on June 4, 2020

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 !
'''
💖 💪 🙅 🚩
paurakhsharma
Paurakh Sharma Humagain

Posted on June 4, 2020

Join Our Newsletter. No Spam, Only the good stuff.

Sign up to receive the latest update from our blog.

Related