Python Trick #3: enumerate gives index and value | Python Tips for Beginners


range(len(x)) is clumsy and easy to get wrong. In this Python trick (Day 3 of 30) you will learn: enumerate gives index and value. It takes less than a minute to learn, and you can use it in your next project today.

THE CODE

fruits = ["apple", "kiwi"]

for i, f in enumerate(fruits, 1):

print(i, f)

STEP BY STEP

Pass the list to enumerate.

Add 1 as the start index.

Unpack into i and f in the loop.

WHY IT MATTERS

Using enumerate removes manual counters and off-by-one bugs. It works on any iterable, including files and generators, and the start argument is perfect for numbered output.

TRY IT YOURSELF

Copy the code, change the values, and run it in your editor or a Jupyter notebook. Then write a similar example in the comments and I will check it.

THE 30-DAY SERIES

Every day I share one practical Python trick or solution, from beginner to advanced. Subscribe and turn on notifications so you do not miss the next one. This series is part of my Python, Machine Learning, Deep Learning, Computer Vision, Data Science, LLM and GenAI content.

FOLLOW

Instagram / social: @shaharyarranjah1

#python #pythontips #coding #cleancode #softwareengineer #learnpython #programming #pythonprogramming #codingtips #pythonforbeginners #100daysofcode

Show more Show less