▶ Try It Yourself

Python For Loops

A for loop is used for iterating over a sequence.

The for Loop

A for loop is used for iterating over a sequence (a list, tuple, string, dictionary, set, or range). This is less like the for keyword in other programming languages and works more like an iterator method found in other object-oriented programming languages.

Example — Loop through a list
fruits = ["apple", "banana", "cherry"] for x in fruits: print(x)

Looping Through a String

Even strings are iterable objects — they contain a sequence of characters:

Example — Loop through a string
for x in "banana": print(x)

The range() Function

To loop a set number of times, use the range() function. It returns a sequence of numbers, starting from 0 by default:

Example — Using range()
for x in range(6): print(x)
📝 Note range(6) gives values 0, 1, 2, 3, 4, 5 — it does not include the number 6 itself.

The range() function has two more parameters — start value and step:

Example — range(start, stop, step)
# Start at 2, stop at 30, step by 3 for x in range(2, 30, 3): print(x)

Nested Loops

A nested loop is a loop inside a loop. The "inner loop" will be executed one time for each iteration of the "outer loop":

Example — Nested loops
adj = ["red", "big", "tasty"] fruits = ["apple", "banana", "cherry"] for x in adj: for y in fruits: print(x, y)

break and continue

Example — break (stop the loop)
fruits = ["apple", "banana", "cherry"] for x in fruits: print(x) if x == "banana": break
Example — continue (skip current iteration)
fruits = ["apple", "banana", "cherry"] for x in fruits: if x == "banana": continue print(x)