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

Python for Loop

A for loop goes through a group of things one at a time, like handing out a sticker to every child in a line. You write the steps once and Python repeats them for each item.
Syntax
python
for item in iterable:
    # loop body

for i in range(start, stop, step):
    # loop body

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:  # fruit takes each list item in turn
    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():  # .items() yields both key and value each pass
    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):  # outer loop
    for j in range(2):  # inner loop runs fully for each outer iteration
        print(i, j)
Related Topics
{# common_mistakes/chapter_summary/browser_support: on Hindi pages the view already swaps in the hi_ translation fields (or blanks these out if untranslated), so this renders correctly for both languages without a lang_code check here. #}
Common Mistakes
  1. Looping with for i in len(items):, which raises TypeError; use range(len(items)) or iterate the list directly.
  2. Adding or removing items of a list while iterating over it, which skips elements.
  3. Expecting range(5) to include 5; it stops at 4.

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.