← Back to Python Course | Chapter 3: Control Flow | Lesson 6 of 10

Python for Loop

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

python
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

python
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

python
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

python
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

python
for i in range(2):
    for j in range(2):
        print(i, j)

Login to run this code

C/C++/Java/PHP execution requires a free account. Your code is saved — you'll land right back in the editor after logging in.