Python for Loop
In this page:
Iterating over Lists
A for loop steps through each item in a sequence — a list, string, tuple, or other iterable — one at a time automatically, without you needing to manage an index counter yourself the way you would in a while loop.
Example: Iterating over Lists
fruits = ["apple", "banana", "cherry"]
for fruit in fruits:
print(fruit)
Iterating with Range
range() generates a sequence of numbers on demand rather than storing them all in memory, making for i in range(10): the standard way to run a block a fixed number of times.
Example: Iterating with Range
for i in range(5):
print(i)
Looping through Strings
Looping over a string with for char in text: visits each individual character in order, which is the basis for tasks like counting vowels, reversing text manually, or validating that every character meets some rule.
Example: Looping through Strings
for char in "cat":
print(char)
Iterating over Dictionaries
Iterating directly over a dictionary loops through its keys by default; use .items() instead if you need both the key and its corresponding value on each pass, or .values() if you only need the values.
Example: Iterating over Dictionaries
user = {"name": "Alex", "age": 30}
for key, value in user.items():
print(key, value)
Nested For Loops
Placing a for loop inside another for loop runs the inner loop to completion for every single iteration of the outer one — the standard technique for working through two-dimensional structures like a grid or a list of lists.
Example: Nested For Loops
for i in range(2):
for j in range(2):
print(i, j)
Chapter Quiz — Complete all 10 topics to unlock
0/10 topics done
Complete these topics first: