Python is a general-purpose, high-level programming language. It's one of the most popular languages due to being versatile, simple, and easy to read.
A for
loop helps iterate through elements in a sequence object (such as a list, tuple, set, dictionary, string, or generator). It enables running a set of commands for each item until a terminating condition.
This guide shows how to use for
loops in Python through examples.

Prerequisites
- Python 3 installed.
- A Python-friendly IDE or text editor to test the code.
Note: To install Python 3, follow one of our guides for your OS:
When to Use for Loop in Python?
A for
loop in helps simplify repetitive tasks in Python by looping over a collection. The construct iterates over sequence-like data structures or a generator function.
Use a for
loop to:
- Go through each item in a sequence a specific number of times.
- Access each element in a collection one by one.
- Perform an action for each item.
The for
loop is a common structure when working with iterators and generators. It automatically increments a counter using a clean and readable syntax.
Python for Loop Syntax
The basic for
loop syntax in Python is:
for variable in iterable:
# Code block
The syntax contains the following elements:
variable
. The variable that takes on each value from the iterable.iterable
. A sequence or collection to loop through.
The indented code block inside the for
loop executes once for each item in the iterable.
Python for Loop Examples
Using a for
loop is an essential task when working with iterables in Python. The following sections show working examples with different data types and use cases.
List Loop
Use a for loop with lists to iterate through items:
my_list = ["Alice", "Bob", "Charlie"]
for item in my_list:
print(item)
The loop prints each item in the list one at a time.
String Loop
In Python, Strings are iterable objects. Use a for loop to go through a string's characters:
for character in "Alice":
print(character)
The code prints each character from the string in a new line.
Dictionary Loop
Looping through a dictionary provides access to its keys:
my_dictionary = {"name": "Alice", "age": 40}
for key in my_dictionary:
print(key, my_dictionary[key])
The loop prints each key and its corresponding value. Alternatively, use .items()
to access both keys and values:
my_dictionary = {"name": "Alice", "age": 40}
for key, value in my_dictionary.items():
print(key, value)
This approach prints the key-value pairs in the dictionary.
Tuple Loop
Tuples are another iterable similar to lists, but immutable:
my_tuple = ("Alice", "Bob", "Charlie")
for item in my_tuple:
print(item)
The loop accesses and prints each element of the tuple.
Set Loop
Sets are also an iterable in Python. They are unordered collections that have unique elements.
For example:
my_set = {1, 2, 3}
for item in my_set:
print(item)
The loop prints each number from the set. Since sets are unordered, the order of numbers may vary.
Loop with range()
The range()
function allows looping a specific number of times:
for i in range(5):
print(i)
It generates numbers from 0 to 4 and prints each number.
Loop with enumerate()
To find the index for an item along with a list item, use the enumerate()
function:
my_list = ["Alice", "Bob", "Charlie"]
for index, item in enumerate(my_list):
print(index, item)
The code prints each item and its index.
Loop with zip()
The zip()
function allows iterating over multiple sequences at the same time:
names = ["Alice", "Bob", "Charlie"]
ages = [40, 50, 60]
for name, age in zip(names, ages):
print(name, age)
The loop with zip()
creates pairs from the two lists and prints them together.
Nested for Loops
Nested for loops enable iterating through multi-dimensional lists. For example, a two-dimensional list requires two nested for
loops to access individual items:
matrix_2d = [[1, 2], [3, 4]]
for row in matrix_2d:
for column in row:
print(column)
The code accesses and prints each element.
Generator Function
A generator function evaluates values one at a time when invoked (lazily). They are compatible with for
loops:
def countdown(n):
while n > 0:
yield n
n -= 1
for number in countdown(5):
print(number)
The loop uses a generator function as a custom iterator to count down from 5 to 1.
Loop With Conditional Logic
Add if
statements to check for conditions inside a for
loop:
my_list = [1, 2, 3, 4, 5]
for number in my_list:
if number % 2 == 0:
print(number)
The statement checks and prints a number if it is divisible by two.
Loop with break and continue
Use the break
statement to exit early or continue
to skip an iteration in a for
loop:
for i in range(5):
if i == 1:
continue
if i == 4:
break
print(i)
The statements check the counter's value, skips if it's 1 and stops before printing 3.
Loop and List Comprehension
A simple and compact way to create a new list with a for loop is to use list comprehension:
cubes = [x**3 for x in range(5)]
print(cubes)
The statement creates a list of cubes in the provided range.
Troubleshooting Python for Loop Issues
Working with for
loops in Python can lead to several potential issues that require troubleshooting. Although the syntax is simple, the logic behind how iterables work, variable scope, and loop statement behavior can introduce complexity.
The list below shows the most obvious mistakes to avoid and fix:
- Looping over non-iterables. Data types such as
int
are not iterable. Convert a non-iterable usingrange()
orstr()
(depending on the code). - Bounds errors. The
range()
function stops before the provided bound. Therefore,range(5)
goes from 0 to 4. - Flow order. A misplaced break or continue statement can skip essential code.
- Shadowing. Ensure variable names don't overwrite built-ins (i.e., using
list
as a variable name). - Using a
for
loop instead ofwhile
is better. If the stopping condition is not based on iteration count, use awhile
loop instead.
The sections below explain complex cases when troubleshooting Python for
loops.
Modifying Lists While Iterating
Removing items from a list while looping over it can cause unpredictable behavior. It leads to skipping elements unexpectedly.
For example:
numbers_list = [2, 4, 6, 8]
for number in numbers_list:
if number % 2 == 0:
numbers_list.remove(n)
Python uses an internal counter during iteration. Removing an element shifts the list and causes the loop to skip some elements. The code should return an empty list, but due to removing items and shifting, it does not.
To resolve this issue, there are two possible options:
- Use a list copy (
[:]
):
numbers_list = [2, 4, 6, 8]
for number in numbers_list[:]:
if number % 2 == 0:
numbers_list.remove(number)
- Build a new list:
numbers_list = [2, 4, 6, 8]
new_list = [number for number in numbers_list if number % 2 != 0]
Loop Variable Persistence
A loop variable can overwrite existing variables and persist after the loop, which can lead to bugs later in the code:
i = 2
for i in range(5):
pass
print(i)
Avoid using loop variables before or after the loop, unless it's intentional. Use different variable names outside the loop to avoid confusion, overwriting existing variables, or variable leakage.
Conclusion
This guide showed how for
loops work in Python. We provided hands-on examples, different use cases, and how to troubleshoot common issues.
Next, see how to use a for
loop to read a file line by line in Python.