Understanding the For Loop
A for
loop in Python is used to iterate over a sequence (like a list, tuple, string, or range) or other iterable objects. It’s a concise way to perform actions on each item in a collection.
Basic Syntax:
Python
for item in iterable:
# code to be executed for each item
Iterating Over Sequences
Python
fruits = ["apple", "banana", "cherry"]
for fruit in fruits:
print(fruit)
The range()
Function
The range()
function generates a sequence of numbers.
Python
for i in range(5):
print(i) # Output: 0, 1, 2, 3, 4
Key Points
- The loop variable (e.g.,
fruit
ori
) takes on the value of each item in the sequence during each iteration. - The loop continues until all items in the sequence have been processed.
- You can use
break
to exit the loop prematurely andcontinue
to skip the current iteration.
Common Use Cases
- Iterating over lists, tuples, and strings.
- Generating sequences of numbers with
range()
. - Processing data from files or other sources.
How does a for loop work?
The for loop iterates through each item in the sequence, assigning it to a loop variable.
Can I use a for loop with strings?
Yes, strings are iterable sequences of characters.
Can I modify a list while iterating over it?
It’s generally not recommended to modify a list while iterating over it. Create a copy if necessary.
Can I use a for loop with a dictionary?
Yes, you can iterate over the keys or values of a dictionary.
What is the enumerate()
function?
enumerate()
returns both the index and value of each item in a sequence.
How can I improve for loop performance?
Consider using list comprehensions or generator expressions for efficiency.