This guide explains for Loops: Iterate over Sequences through a focused example and practical reasoning. No prior knowledge of this specific operation is required.
Understanding the Concept
A for loop obtains items from an iterable, including a list, string, tuple, range or dictionary. It handles advancing to the next item automatically.
When You Would Use This
Print product labels from a small list.
Step-by-Step Example
product_names = ["Notebook", "Marker", "Folder"]
for product_name in product_names:
print("Product:", product_name)
How the Example Works
The loop binds product_name to each list element in order and executes the body three times. It does not modify the list.
Example Output
Product: Notebook
Product: Marker
Product: Folder
Try It Yourself
Loop through the characters of one product name and print one character per line.
Common Beginner Mistakes
- Using a manual counter for every simple iteration.
- Forgetting that iterating over a dictionary visits keys by default.
- Changing a list’s size while iterating over it.
Key Takeaways
- A
forloop obtains items from an iterable, including a list, string, tuple, range or dictionary. - The loop binds
product_nameto each list element in order and executes the body three times. - Avoid this mistake: Using a manual counter for every simple iteration.