Python for Loop: Syntax, Usage, Examples

By
Milica Dancuk
Published:
June 4, 2025
Topics:

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.

How to Use for Loops in Python

Prerequisites

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)
Python for loop list output

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)
Python for loop string output

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])
Python for loop dictionary key output

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)
Python for loop dictionary key value output

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)
Python for loop tuple output

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)
Python for loop set output

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)
Python for loop range() output

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)
Python for loop enumerate() output

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)
Python for loop zip() output

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)
Python nested for loop output

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)
Python for loop generator function output

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)
Python for loop and if statement output

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)
Python for loop break and continue output

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)
python for loop list comprehension output

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 using range() or str() (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 of while is better. If the stopping condition is not based on iteration count, use a while 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)
Removing from list while iterating Python output

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)
Removing from list copy Python output
  • Build a new list:
numbers_list = [2, 4, 6, 8]
new_list = [number for number in numbers_list if number % 2 != 0]
Removing from list comprehension Python output

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)
Loop variable persistence  output

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.

Was this article helpful?
YesNo