How to iterate a list in Python
Use `for item in lst`. When you need the index too, use enumerate(lst).
fruits = ["apple", "banana", "cherry"]
for fruit in fruits:
print(fruit)
for i, fruit in enumerate(fruits):
print(f"{i}: {fruit}")The bare `for item in lst` is the Python idiom β never write `for i in range(len(lst)): item = lst[i]`. It's harder to read and slower because of the double lookup.
When you DO need the index, enumerate() gives you both without the boilerplate. It defaults to 0-based; pass start=1 if you want 1-based like line numbers or lesson numbers.
Parallel iteration over multiple lists uses zip: `for name, age in zip(names, ages)`. If the lists might differ in length, use itertools.zip_longest β plain zip silently stops at the shortest input.
Variations
Index AND value with enumerate
for i, name in enumerate(["Alice", "Bob"], start=1):
print(f"{i}. {name}")start= controls the first index.
Two lists in lockstep
names = ["Alice", "Bob"]
ages = [30, 25]
for name, age in zip(names, ages):
print(name, age)zip is your friend β never write parallel index-loops.
Modify while iterating (copy first!)
nums = [1, 2, 3, 4]
for n in nums[:]: # slice = copy
if n % 2 == 0:
nums.remove(n)Never mutate the same list you're iterating β behaviour is undefined.
Get one Python lesson + one career idea every Friday
No spam, no "buy our course now". Three bullets, every Friday. Unsubscribe with one click.