Skip to content

for

In Python, the for keyword creates a loop that iterates over an iterable, such as a list, tuple, string, or range.

It also lets you define comprehensions and generator expressions. You can think of loops as a tool to execute a block of code repeatedly for each item in the sequence. Similarly, comprehensions are expressions that you can use to create lists, dictionaries, and sets.

Python for Keyword Examples

Here’s a quick example of how you can use the for keyword in a Python loop:

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

In this example, the for loop iterates over each item in the fruits list. For every iteration, the current item is stored in the variable fruit, and the print() function outputs its value. This loop continues until all items in the list have been processed.

Here’s an example of for in a comprehension:

Python
>>> squares = [number**2 for number in range(10)]
>>> squares
[0, 1, 4, 9, 16, 25, 36, 49, 64, 81]

This comprehension iterates over a range of numbers, computes their square values, and build a new lists with them.

Python for Keyword Use Cases

  • Iterating over elements in a sequence, such as lists, tuples, strings, and ranges
  • Executing a block of code for each item in a collection
  • Implementing common patterns like summing numbers, generating sequences, or filtering items from a collection.
  • Simplifying code with comprehensions and generator expressions

Tutorial

Python for Loops: The Pythonic Way

Learn how to use Python for loops to iterate over lists, tuples, strings, and dictionaries with Pythonic looping techniques.

intermediate best-practices python

For additional information on related topics, take a look at the following resources:


By Leodanis Pozo Ramos • Updated Feb. 9, 2026 • Reviewed by Dan Bader