Python For Loop: Syntax, Usage, and Examples

Python for loops are control flow statements that iterate over a sequence, such as a list, tuple, dictionary, set, or string. They are ideal for executing a block of code a certain number of times or going through items in a collection.

How to Use the For Loop in Python

The syntax of a for loop in Python is simple and straightforward. Here's a basic example to demonstrate the structure:

# Iterating over a sequence
for item in sequence:
    # Code to execute for each item
  • for: The keyword that starts the for loop.
  • item: A variable that takes the value of the item in the sequence for each iteration.
  • in: The keyword that links the variable to the sequence.
  • sequence: The collection you want to iterate over.

When to Use the For Loop in Python

In Python, for loops can be valuable in many scenarios. You can use for loops to iterate through elements in a list, characters in a string, or key-value pairs in a dictionary. For loops are particularly useful when you know how many iterations you need. They're also great when you want to apply an operation to each item in a sequence.

Examples of For Loops in Python

For loops are a staple in Python programming. Here are some practical examples:

List Iteration

Iterating over a list is a common use case for for loops in Python programming. With a for loop, you can perform operations on each item within the list. This can be particularly useful for processing collections of data. As an example, consider performing calculations on a list of numbers or working with a list of strings.

colors = ["red", "green", "blue"]
for color in colors:

Range Function

While range() is extremely common in for loops, it’s not a part of the for loop syntax itself. Similar to the print() function, range() is a built-in Python function. The range() function returns a sequence of numbers. By default, it starts with 0, increments by 1, and stops before a specified integer.

for i in range(5):  # Creates a range from 0 to 4

The functionality of the range() function aligns perfectly with the for loop's requirement to iterate over a sequence. Providing iterable objects with integers, range() allows you to execute a block of code a specific number of times. For example, for i in range(5) iterates over a sequence of numbers from 0 to 4.

Dictionary Iteration

Dictionaries in Python are key-value pairs. Iterating over them using for loops can be highly effective for accessing and modifying their contents. This is particularly useful for tasks that involve mapping keys to values, such as processing user data or configurations.

user_info = {"name": "John", "age": 30}
for key, value in user_info.items():
    print(f"{key}: {value}")

Nested For Loops

Nested for loops are powerful for working with more-dimensional data structures, like matrices or nested lists. They're useful for a wide range of applications, from image processing to game development.

matrix = [[1, 2, 3], [4, 5, 6], [7, 8, 9]]
for row in matrix:
    for item in row:

Learn More About the For Loop in Python

For Loop vs. While Loop

For loops and while loops are both fundamental to Python but serve different purposes based on the situation.

A for loop is ideal when there's a defined number of iterations, such as when looping over a list or a range. This feature makes for loops the go-to choice for iterating over fixed-length sequences.

On the other hand, a while loop is more suited to situations where there's an undefined number of iterations. Monitoring systems triggering an alarm at certain temperatures are a great use case for a while loop.

Break Statements in For Loops

A break statement in a for loop allows you to exit the loop before it has gone through all items in the sequence. This is particularly useful for stopping the loop when a specific condition becomes true.

As an example, consider a for loop that iterates through a list of commands. You can use break to exit the loop if the user enters a "quit" command:

commands = ["start", "pause", "quit", "restart"]
for command in commands:
    if command == "quit":
        break  # Exit the loop
    print(f"Processing {command}")

Continue Statements in For Loops

A continue statement in a for loop skips the current iteration and proceeds to the next one. This can be handy when you want to ignore specific items in the sequence.

Consider a for loop iterating over a data set. Using continue, you can skip over any data points that don’t meet a certain criterion. Instead, you can focus on the relevant ones:

data_points = [1, 2, -1, 4, -5, 6]
for data in data_points:
    if data < 0:  # Skip negative numbers
    print(f"Processing data point: {data}")

However, break and continue statements can also make your code difficult to understand. You can avoid unintended consequences by using break and continue statements judiciously.

Learn to Code in Python for Free
Start learning now
button icon
To advance beyond this tutorial and learn Python by doing, try the interactive experience of Mimo. Whether you're starting from scratch or brushing up your coding skills, Mimo helps you take your coding journey above and beyond.

Sign up or download Mimo from the App Store or Google Play to enhance your programming skills and prepare for a career in tech.

You can code, too.

© 2023 Mimo GmbH