Table of Contents
What Will You Learn
This section teaches you how to use for loops in Python to iterate over sequences like lists, strings, ranges, and dictionaries. You'll understand loop structure, the role of the range() function, and how to use break, continue, and else within loops. These fundamentals are essential for repetitive tasks and data processing.
The for
loop is one of the most essential tools for any programmer working with Python. It allows you to repeat a block of code a specific number of times or iterate
over items in a sequence like a list, tuple, or string. Without loops, repetitive tasks would have to be written manually, making code inefficient and harder to maintain.
In this section, you'll learn exactly how for
loops work, when to use them, and what makes them powerful and readable in Python. We'll cover basic syntax, practical
variations, and common patterns. Whether you're iterating over numbers, indexes, or multiple sequences at once, mastering for
loops is a must for writing clean and
logical Python code.
What Is a For Loop in Python?
A for
loop in Python is used to iterate over a sequence of values. It goes through each item, one at a time, and runs a block of code for each iteration. Unlike in
many other programming languages, Python’s for
loop doesn’t require manually initializing counters or managing the loop’s end condition — it
works directly with iterables.
The loop uses the in
keyword to iterate over a list, string, tuple, dictionary, or any iterable object. It’s clean, easy to read, and eliminates the need for
traditional counting loops in most scenarios. Python also offers built-in functions like range()
and enumerate()
that enhance the power and flexibility
of for
loops. From traversing lists to parallel iteration, Python handles it efficiently.
Here are some common ways to use for
loops in Python:
- Inline for loop (Python list comprehension). A concise way to generate lists using
for
. - For loop with index. Iterate using a range to access index and values.
- Enumerate for loop. Use
enumerate()
to get index and value directly. - Backwards for loop. Iterate in reverse using
reversed()
orrange()
. - Parallel for loop. Use
zip()
to iterate over two lists simultaneously.
squares = [x * x for x in range(5)]
for i in range(len(items)):
print(i, items[i])
for index, value in enumerate(items):
print(index, value)
for i in reversed(range(5)):
print(i)
for name, score in zip(names, scores):
print(f"{name}: {score}")
How to Do a For Loop in Python?
To perform a for
loop in Python, you use the for
keyword followed by a variable name, the in
keyword, and the iterable you want to loop
through. The indented block of code below the loop runs once for each item in the sequence. Python automatically handles iteration and updates the loop variable with each new
value. This makes the for
loop ideal for working with lists, strings, dictionaries, ranges, and other iterable objects. The loop ends when the iterable is exhausted
— you don't need to manually increment counters or check stop conditions. This approach leads to clean, readable code that is easy to write and understand. You can also use
helper functions like range()
or enumerate()
to enhance the loop’s behavior.
How to Write a For Loop in Python?
Writing a for
loop in Python is simple and consistent. You start with the for
keyword, followed by a loop variable that represents the current item in
the iteration. Then use the in
keyword followed by the iterable (such as a list or range). A colon :
marks the start of the loop block, and the indented
code below runs for each element. The loop variable updates automatically on each pass. Here's an example:
for fruit in ["apple", "banana", "cherry"]:
print(fruit)
This loop prints each fruit in the list. The loop variable fruit
takes on the value of each item in the list, one at a time.
You can also use the range()
function to create a sequence of numbers. For example, range(5)
generates numbers from 0 to 4. This is useful for iterating
a specific number of times:
for i in range(5):
print(i)
This loop prints numbers 0 to 4. The loop variable i
takes on each value in the range, allowing you to perform actions based on the current index.
How to End a For Loop in Python?
A for
loop in Python automatically ends when the iterable is fully consumed — no explicit condition or exit command is needed. However, if you want to stop the
loop early, you can use the break
statement. This is useful when a certain condition is met and there's no need to continue iterating. Another approach is using
return
if the loop is inside a function and you want to exit completely. You can also use a pass
statement as a placeholder inside a loop if no action
is required. Here's an example using break
:
for num in range(10):
if num == 5:
break
print(num)
This loop stops when num
reaches 5, printing only 0 to 4.
Common Mistakes Made by Beginners
1. Forgetting the colon at the end of the for
line
Beginners often forget the colon :
at the end of the for
loop declaration, which leads to a SyntaxError
.
Incorrect:
for i in range(5)
print(i)
Fix: Always add a colon.
for i in range(5):
print(i)
2. Not using indentation
In Python, indentation defines code blocks. If you forget to indent the loop body, Python throws an IndentationError
.
Incorrect:
for i in range(3):
print(i)
Fix: Indent the body by 4 spaces or 1 tab.
for i in range(3):
print(i)
3. Modifying the loop variable inside the loop
Changing the loop variable manually inside the loop may cause logical errors and confusion.
Problem:
for i in range(5):
i += 1
print(i)
Fix: Let Python handle iteration. Use other variables if needed.
4. Using range()
on a non-integer
Beginners mistakenly try to use range()
with non-integer values, like floats or strings, which raises a TypeError
.
Incorrect:
for i in range(0, 5.5):
print(i)
Fix: Ensure all arguments to range()
are integers.
for i in range(6):
print(i)
5. Using break
without a condition
Calling break
with no conditional check ends the loop immediately, which may not be intended.
Problem:
for i in range(10):
print(i)
break
Fix: Use break
only inside a meaningful if
condition.
6. Looping over an empty list or wrong iterable
Trying to iterate over None
or an empty list won’t raise an error, but nothing will execute.
Problem:
data = None
for item in data:
print(item)
Fix: Check that the iterable is not None
or empty before the loop:
if data:
for item in data:
print(item)
FAQ – For Loop in Python
1. How to make a for
loop in Python?
To create a for
loop in Python, use the for
keyword followed by a loop variable, the in
keyword, and an iterable object (like a list,
tuple, or range). End the line with a colon, and indent the block of code to be executed in each iteration. Example:
for i in range(5):
print(i)
This loop prints numbers 0 through 4. Python automatically manages the iteration without manual counter updates. The loop ends when the iterable is exhausted. You can use
range()
, enumerate()
, or zip()
to enhance the loop depending on your needs. Avoid modifying the loop variable inside the block unless you
fully understand the implications.
2. What is the difference between for
loop and while
loop in Python?
A for
loop iterates over a sequence of known length or structure (like a list, string, or range), while a while
loop continues running as long as a
condition is True
. The key difference is predictability: for
loops are typically used when you know how many times to iterate, and
while
loops are used when the number of iterations is unknown in advance.
Example:
# For loop
for i in range(5):
print(i)
# While loop
i = 0
while i < 5:
print(i)
i += 1
Use for
when iterating over items. Use while
for open-ended conditions.
3. How to skip an iteration in a for
loop in Python?
You can skip the current iteration in a for
loop by using the continue
statement. When Python hits continue
, it immediately jumps to the
next iteration of the loop, skipping all remaining code below it for that cycle.
Example:
for i in range(5):
if i == 2:
continue
print(i)
This prints 0, 1, 3, and 4 — skipping 2. It’s useful for filtering out unwanted items, skipping invalid data, or bypassing specific conditions. Avoid using it excessively, as it can reduce code readability.
4. How to reverse a list in Python using a for
loop?
To reverse a list using a for
loop, you can either iterate over the list using reversed()
or use a descending range()
with the last
index.
Example using reversed()
:
for item in reversed(my_list):
print(item)
Or using indexes:
for i in range(len(my_list)-1, -1, -1):
print(my_list[i])
Both approaches achieve the same goal. reversed()
is more readable and Pythonic, while the range()
version gives you more control over indexing.
5. Can I use for
loops to iterate over dictionaries?
Yes, Python allows for
loops to iterate over dictionaries. By default, looping over a dictionary returns its keys. You can also access values or key-value pairs
using .values()
or .items()
.
Example:
data = {'a': 1, 'b': 2}
for key in data:
print(key)
for value in data.values():
print(value)
for key, value in data.items():
print(key, value)
This flexibility makes for
loops ideal for working with structured data. Just remember that dictionaries are unordered in versions below Python 3.7.
6. How to use for
loop with conditional logic inside?
You can include if
statements inside a for
loop to execute code only for certain items that meet a condition.
Example:
for num in range(10):
if num % 2 == 0:
print(f"{num} is even")
This loop prints only even numbers from 0 to 9. You can also combine this with continue
, break
, or nested logic to control how and when certain
operations happen during iteration. This is a powerful pattern used in filtering, validation, and selective processing.