3.2 for Loops
Exploring the for loop for iterating over sequences like strings, lists, and dictionaries, as well as using the range() function for numerical iterations.
The `for` loop is used to repeat the execution of a block of code for each item in a sequence (iterable). Sequences in Python include strings, lists, tuples, sets, dictionaries, and objects created by the `range()` function.
Syntax
`for loop_variable in sequence:\n # Code executed for each item`
In each iteration, the `loop_variable` takes the value of the next item in the sequence.
Iterables: The Heart of the for Loop
An "iterable" is any object in Python that can be iterated over. The `for` loop asks the iterable for an "iterator," which is an internal object that knows how to provide the next item of the sequence each time it is asked, until the items are exhausted.
The else Statement in for Loops
A lesser-known feature is the `else` clause in loops. The code block under `else` is executed **only if the loop completes all its iterations normally**, without being interrupted by a `break` statement. It is useful for executing code when a search in a loop did not find what it was looking for.
The enumerate() Function
Often, you want to access both the index and the value of an item during iteration. `enumerate()` is the ideal way to achieve this, returning a pair (index, value) in each iteration.
# Example 1: for loop with a list
fruits = ["apple", "banana", "cherry"]
print("The fruits are:")
for fruit in fruits:
print(fruit)
print("-" * 30)
# Example 2: for loop with the range() function
# The range() function generates a sequence of numbers.
# range(end): Generates numbers from 0 to (end - 1)
print("Numbers from 0 to 4:")
for i in range(5):
print(i)
print("-" * 30)
# range(start, end, step): Generates numbers from 'start' to (end - 1), with 'step'
print("Even numbers from 0 to 9:")
for j in range(0, 10, 2):
print(j)
Explore More with AI
Use AI to generate new examples, delve deeper into theory, or get your questions answered.