How do I get the index while looping in Python?
Short answer
Use enumerate(items), which yields (index, value) pairs. Pass start=1 when the numbers are for humans to read.
lessons = ["Intro", "Basics", "Loops"]
for index, lesson in enumerate(lessons):
print(index, lesson) # 0 Intro, 1 Basics, 2 Loops
for number, lesson in enumerate(lessons, start=1):
print(f"Lesson {number}: {lesson}") # Lesson 1: Intro, ...start=1 is the part people miss and then compensate for with index + 1 scattered through their output strings.
#The anti-pattern it replaces
for i in range(len(lessons)): # works, but verbose
print(i, lessons[i])If you only need the values, loop over the list directly. If you need the position too, that is what enumerate is for. range(len(...)) is almost never the right answer.
#It works in comprehensions too
numbered = [f"{i}. {name}" for i, name in enumerate(lessons, 1)]#Two lists at once
enumerate gives you index plus one sequence. For two sequences, use zip:
for name, count in zip(names, counts):
print(name, count)And for both at once:
for i, (name, count) in enumerate(zip(names, counts), 1):
print(i, name, count)