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: The Pythonic Way
In this tutorial, you'll learn all about the Python for loop. You'll learn how to use this loop to iterate over built-in data types, such as lists, tuples, strings, and dictionaries. You'll also explore some Pythonic looping techniques and much more.
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)
- Python "for" Loops: The Pythonic Way (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)