Robert Johns | 05 Mar, 2025
Fact checked by Jim Markus

Python For Loop | Docs With Examples

The Python for loop is a fundamental control structure that allows you to iterate over iterable objects such as lists, tuples, strings, dictionaries, and more. It simplifies repetitive tasks by automating iteration through a sequence of elements.

Python for Loop Syntax

Most of your Python projects will contain for loops, so let's check out the basic syntax:

for loop_variable in sequence:
    # Block of code to execute

The loop iterates over each item in the sequence, assigning it to loop_variable and executing the block of code within the loop body.

Looping Through a List

fruits = ["apple", "banana", "cherry"]
for fruit in fruits:
    print(fruit)

Output:

apple
banana
cherry

Using for Loop with range()

The Python range() built-in function generates a sequence of integers, often used with for loops.

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

Output:

0
1
2
3
4

You can also specify a start, stop, and step value. Open up your own Python editor to see for yourself:

for i in range(1, 10, 2):
    print(i)

Output:

1
3
5
7
9

Iterating Over a String

for char in "Python":
    print(char)

Output:

P
y
t
h
o
n

Looping Through a Dictionary

student_scores = {"Alice": 85, "Bob": 90, "Charlie": 78}
for key, value in student_scores.items():
    print(f"{key}: {value}")

Output:

Alice: 85
Bob: 90
Charlie: 78

Here, each key-value pair is accessed and printed.

Using else with a for Loop

Python allows an else block to execute after a for loop completes normally.

for i in range(3):
    print(i)
else:
    print("Loop completed!")

Output:

0
1
2
Loop completed!

However, if the loop is terminated using break, the else block will not execute.

Breaking Out of a for Loop with break

for num in range(10):
    if num == 5:
        print("Stopping at 5")
        break
    print(num)

Output:

0
1
2
3
4
Stopping at 5

Skipping an Iteration with continue

for num in range(5):
    if num == 2:
        continue
    print(num)

The continue statement is used to skip the current iteration and move to the next iteration.

Output:

0
1
3
4

Using pass in a for Loop

for i in range(5):
    pass  # Placeholder for future implementation

The pass statement allows you to create a placeholder for future code.

Using for Loops to Repeat a Task a Specific Number of Times

for _ in range(3):
    print("Hello!")

If you need to repeat a task a specific number of times, you can use for loops with range():

Output:

Hello!
Hello!
Hello!

Nested for Loops

for i in range(3):
    for j in range(2):
        print(f"i={i}, j={j}")

A for loop can be placed inside another loop to iterate over multiple sequences. The outer loop controls the rows, while the inner loop iterates within each row.

Output:

i=0, j=0
i=0, j=1
i=1, j=0
i=1, j=1
i=2, j=0
i=2, j=1

Comparison: for Loop vs while Loop

# For loop example
for i in range(3):
    print(i)

# While loop example
i = 0
while i < 3:
    print(i)
    i += 1

A for loop iterates over a sequence, while a Python while loop continues executing as long as a condition remains true.

Both will print the same output but use different loop syntax.

Common Questions

Can Python loops have an else clause?

Yes, Python loops can have an else clause. The else block executes after the for loop completes normally (without encountering a break statement). If the loop is terminated early with break, the else block will not run.

How to break a Python for loop?

for i in range(10):
    if i == 5:
        break
    print(i)

You can use the break statement to exit a loop early when a specific condition is met:

This will stop execution when i equals 5.

Are Python for loops inclusive?

No, Python for loops using range() are exclusive of the stop value. For example:

for i in range(1, 5):
    print(i)

Output:

1
2
3
4

The loop stops before reaching 5.

Can you put a for loop in a function in Python?

Yes, a for loop can be placed inside a function you define to iterate over elements and return results.

def print_numbers(n):
    for i in range(n):
        print(i)

print_numbers(3)

Output:

0
1
2

Can you nest for loops in Python?

Yes, you can nest for loops in Python. A nested loop is useful for iterating over multi-dimensional structures like matrices.

for i in range(2):
    for j in range(3):
        print(f"i={i}, j={j}")

This loops through both i and j values.

Best Practices for Python for Loops

  • Use enumerate() when you need both index and value.
  • Use list comprehensions for concise loop operations.
  • Avoid modifying a list while iterating over it.
  • Use break and continue wisely to control loop execution.

Key Takeaways

  • The for loop in Python iterates over sequences like lists, strings, and dictionaries.
  • The range() function is commonly used to generate numeric sequences.
  • break, continue, and else can control loop behavior.
  • Nested loops allow multi-level iteration.
  • It's better to use a while loop when conditions need to be met dynamically.

Wrapping Up

The for loop is one of Python’s most powerful features, making iteration easy and efficient. Understanding how to use for loops effectively will help you write cleaner, more efficient code. Whether iterating over lists, dictionaries, or ranges, mastering for loops is essential for Python development.

By Robert Johns

Technical Editor for Hackr.io | 15+ Years in Python, Java, SQL, C++, C#, JavaScript, Ruby, PHP, .NET, MATLAB, HTML & CSS, and more... 10+ Years in Networking, Cloud, APIs, Linux | 5+ Years in Data Science | 2x PhDs in Structural & Blast Engineering

View all post by the author

Subscribe to our Newsletter for Articles, News, & Jobs.

I accept the Terms and Conditions.

Disclosure: Hackr.io is supported by its audience. When you purchase through links on our site, we may earn an affiliate commission.

In this article

Learn More

Please login to leave comments