Last updated

Python For Loops

Definition: A for loop goes through the items of a collection (a list, a string, a range) one item at a time. It is the most common loop in Python.

Example 1 — looping over a list

fruits = ["apple", "banana", "cherry"]
for fruit in fruits:
    print(fruit)

Read it as "for each fruit in the list, print it".

Example 2 — looping over a string

for letter in "Sam":
    print(letter)

Example 3 — repeating with range()

range(5) gives 0,1,2,3,4. range(1, 6) gives 1,2,3,4,5:

for i in range(5):
    print(i)

for i in range(1, 6):
    print("Step", i)

Example 4 — a running total

numbers = [10, 20, 30]
total = 0
for n in numbers:
    total += n
print("Total:", total)

Example 5 — counting matches

words = ["hi", "hello", "hey", "yo"]
count = 0
for w in words:
    if w.startswith("h"):
        count += 1
print("Words starting with h:", count)

💡 for vs while: use for when you know what you are looping over; use while when you are waiting for a condition.

Try it Yourself
Output

          
Ad · responsive