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:
>>> 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:
>>> 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
Related Resources
Tutorial
Python "for" Loops (Definite Iteration)
In this introductory tutorial, you'll learn all about how to perform definite iteration with Python for loops. You’ll see how other programming languages implement definite iteration, learn about iterables and iterators, and tie it all together to learn about Python’s for loop.
For additional information on related topics, take a look at the following resources:
- When to Use a List Comprehension in Python (Tutorial)
- Python Dictionary Comprehensions: How and When to Use Them (Tutorial)
- Python Set Comprehensions: How and When to Use Them (Tutorial)
- For Loops in Python (Definite Iteration) (Course)
- The Python for Loop (Quiz)
- Understanding Python List Comprehensions (Course)
- When to Use a List Comprehension in Python (Quiz)
- Building Dictionary Comprehensions in Python (Course)
- Python Dictionary Comprehensions: How and When to Use Them (Quiz)