Python for Loops: Complete Beginner Guide

Published on: July 10, 2026
Reading time: 4 minutes
ícone de loop com o texto 'For' abaixo

Python for loops repeat a block of code for every item in an iterable. They are used to process lists, read files, transform data, generate reports, validate records, and automate repetitive operations.

Unlike loops in some languages, Python’s for statement usually iterates directly over values instead of manually controlling an index. That design makes common loops concise and readable.

Your first for loop

languages = ["Python", "JavaScript", "Go"]

for language in languages:
    print(language)

During each iteration, language receives the next item. The indented block runs once per item.

The official Python control-flow tutorial explains how for differs from index-based loops in other languages.

What is an iterable?

An iterable is an object that can provide values one at a time. Common iterables include strings, lists, tuples, sets, dictionaries, ranges, files, and generators.

for character in "Python":
    print(character)
for number in (10, 20, 30):
    print(number)

The collection-specific guides to lists, tuples, and sets explain how each iterable behaves.

Using range()

range() produces a sequence of integers without building a full list in memory:

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

This prints 0 through 4. The stop value is excluded.

Use start and stop:

for number in range(1, 6):
    print(number)

Add a step:

for number in range(0, 11, 2):
    print(number)

Count backward with a negative step:

for number in range(5, 0, -1):
    print(number)

The complete guide to Python range() covers start, stop, step, negative values, and common off-by-one errors.

When an index is actually needed

A beginner may write:

names = ["Ava", "Noah", "Mia"]

for index in range(len(names)):
    print(index, names[index])

This works, but enumerate() is clearer:

for index, name in enumerate(names, start=1):
    print(index, name)

Use enumerate() when you need both position and value. The enumerate guide provides additional patterns.

Looping through dictionaries

A dictionary loop returns keys by default:

prices = {"coffee": 3.50, "tea": 2.80}

for product in prices:
    print(product)

Use items() for keys and values:

for product, price in prices.items():
    print(f"{product}: ${price:.2f}")

Use keys() or values() when only one side is needed. The Python dictionaries guide covers safe lookup, nested mappings, and comprehensions.

Looping over two collections with zip()

names = ["Ava", "Noah", "Mia"]
scores = [92, 85, 88]

for name, score in zip(names, scores):
    print(f"{name}: {score}")

zip() stops when the shortest iterable ends. In modern Python, zip(..., strict=True) can raise an error when lengths differ unexpectedly:

for name, score in zip(names, scores, strict=True):
    print(name, score)

break: stop the loop

break exits the nearest loop immediately:

numbers = [4, 8, 15, 16, 23, 42]
target = 16

for number in numbers:
    if number == target:
        print("Found it")
        break

This is useful for searches where no further work is needed after a match.

continue: skip one iteration

continue jumps to the next item:

values = [10, -3, 7, -1, 5]

for value in values:
    if value < 0:
        continue

    print(value)

Use it sparingly. Several continue statements can make a loop difficult to follow.

The else clause on a for loop

A loop’s else block runs when the loop finishes without break:

users = ["ava", "noah", "mia"]
search = "liam"

for user in users:
    if user == search:
        print("User found")
        break
else:
    print("User not found")

This pattern is useful for searches, but a helper function or any() may sometimes be clearer.

Nested for loops

A nested loop runs one loop inside another:

for row in range(1, 4):
    for column in range(1, 4):
        print(f"({row}, {column})")

Nested loops are common for grids, tables, pair comparisons, and matrices. Their total work multiplies. Two loops over collections of size n may perform roughly operations.

Building a multiplication table

for number in range(1, 6):
    print(f"Table for {number}")

    for multiplier in range(1, 11):
        result = number * multiplier
        print(f"{number} × {multiplier} = {result}")

    print()

This project demonstrates nested loops and formatted output.

Modifying a collection while looping

Changing a list or dictionary while iterating over it can skip items or raise an error. Build a new collection instead:

numbers = [1, 2, 3, 4, 5, 6]
even_numbers = []

for number in numbers:
    if number % 2 == 0:
        even_numbers.append(number)

For dictionary deletion, iterate over a copy of the keys:

inventory = {"mouse": 0, "keyboard": 5, "monitor": 0}

for product in list(inventory):
    if inventory[product] == 0:
        del inventory[product]

List comprehensions

A list comprehension is a concise way to transform or filter values:

squares = [number ** 2 for number in range(1, 6)]

Add a condition:

even_squares = [
    number ** 2
    for number in range(1, 11)
    if number % 2 == 0
]

Use a regular loop when the logic requires several steps, error handling, or side effects. The list comprehension tutorial explains when compact syntax improves readability.

Looping through files

A text file is iterable and yields one line at a time:

with open("events.log", encoding="utf-8") as file:
    for line_number, line in enumerate(file, start=1):
        cleaned = line.rstrip()
        print(line_number, cleaned)

This is memory-efficient because Python does not need to load the entire file. See reading TXT files in Python for file modes and line-processing patterns.

Practical project: grade report

students = {
    "Ava": [90, 86, 94],
    "Noah": [72, 80, 77],
    "Mia": [95, 91, 97],
}

for name, grades in students.items():
    average = sum(grades) / len(grades)

    if average >= 90:
        level = "Excellent"
    elif average >= 75:
        level = "Good"
    else:
        level = "Needs improvement"

    print(f"{name:<10} {average:5.1f}  {level}")

This example combines loops, dictionaries, lists, conditionals, arithmetic, and f-string alignment.

Practical project: find duplicate values

values = ["A", "B", "C", "A", "D", "B"]
seen = set()
duplicates = set()

for value in values:
    if value in seen:
        duplicates.add(value)
    else:
        seen.add(value)

print(duplicates)

A set makes membership checks fast. This is generally better than repeatedly searching a growing list.

Practical project: process valid records

records = [
    {"name": "Ava", "age": 29},
    {"name": "", "age": 34},
    {"name": "Mia", "age": -2},
    {"name": "Noah", "age": 41},
]

valid_records = []

for record in records:
    name = record.get("name", "").strip()
    age = record.get("age")

    if not name:
        continue
    if not isinstance(age, int) or age < 0:
        continue

    valid_records.append({"name": name, "age": age})

print(valid_records)

Performance considerations

For loops are appropriate for general Python logic, but libraries such as NumPy and Pandas can process large numeric arrays more efficiently through vectorized operations. Avoid premature optimization; first write correct, readable code, then measure slow sections.

Generators can also avoid storing every result:

squares = (number ** 2 for number in range(1_000_000))

for square in squares:
    if square > 100:
        break

Common mistakes

  • Forgetting indentation.
  • Expecting range() to include the stop value.
  • Using range(len(...)) when only values are needed.
  • Changing a collection during iteration.
  • Writing an accidental infinite loop inside the body.
  • Using too many nested levels instead of extracting functions.
  • Assuming zip() reports different lengths automatically.
  • Using a comprehension for complex, hard-to-read logic.

Best practices

Use descriptive singular variable names, iterate directly over values, choose enumerate() for indexes, choose zip() for parallel collections, extract complex bodies into functions, and keep nesting shallow.

The broader Python loops guide compares for with while and covers additional control-flow patterns.

Conclusion

Python for loops provide a readable way to process any iterable. Master direct iteration, range(), enumerate(), dictionary methods, zip(), break, continue, nested loops, and comprehensions.

Practice by generating a report, filtering records, reading a file, and combining two lists. These exercises represent the loop patterns used in everyday Python work.

Share:

Facebook
WhatsApp
Twitter
LinkedIn

Article content

    Related articles

    Programador pensando enquanto analisa código em dois monitores
    Fundamentals
    Foto de perfil de Leandro Hirt da Academify

    Learn Programming from Scratch: Beginner Guide

    Learn programming from scratch with a practical roadmap covering logic, languages, tools, exercises, projects, debugging, Git, and consistent study habits.

    Ler mais

    Tempo de leitura: 6 minutos
    10/07/2026
    Manipulação e formatação de strings em Python
    Fundamentals
    Foto de perfil de Leandro Hirt da Academify

    Python Strings: Complete Beginner Guide

    Learn Python strings with creation, indexing, slicing, methods, formatting, Unicode, searching, validation, splitting, joining, and practical examples.

    Ler mais

    Tempo de leitura: 4 minutos
    10/07/2026
    código Python de uma tupla com o texto separado formando a frase "O que são tuplas?"
    Fundamentals
    Foto de perfil de Leandro Hirt da Academify

    Python Tuples: Complete Beginner Guide

    Learn Python tuples with creation, packing, unpacking, indexing, immutability, methods, named records, function returns, and practical examples.

    Ler mais

    Tempo de leitura: 5 minutos
    10/07/2026
    símbolo de PI
    Fundamentals
    Foto de perfil de Leandro Hirt da Academify

    Python Floats: Complete Beginner Guide

    Learn Python floats with decimal values, arithmetic, conversion, rounding, precision limits, comparisons, Decimal, math functions, and practical examples.

    Ler mais

    Tempo de leitura: 4 minutos
    10/07/2026
    notebook mostrando tela a teclado
    Fundamentals
    Foto de perfil de Leandro Hirt da Academify

    Python Input and Output: Complete Guide

    Learn Python input and output with input(), print(), conversions, validation, formatting, files, command-line arguments, and practical interactive programs.

    Ler mais

    Tempo de leitura: 4 minutos
    10/07/2026
    Dicionário com o logo do Python em uma página e o texto 'Dicionário Python'
    Fundamentals
    Foto de perfil de Leandro Hirt da Academify

    Python Dictionaries: Complete Beginner Guide

    Learn Python dictionaries from scratch: keys, values, methods, loops, nested data, comprehensions, merging, safe access, and practical examples.

    Ler mais

    Tempo de leitura: 4 minutos
    10/07/2026