A for loop in Python iterates over elements of any iterable object (lists, tuples, strings, dictionaries, generators, or custom iterators) using the standard iterator protocol.
flowchart LR
A["Iterable Object (e.g. list)"] --> B["iter(iterable) -> Iterator"]
B --> C["next(iterator)"]
C --> D{"StopIteration Raised?"}
D -- "No" --> E["Execute Loop Body for Item"] --> C
D -- "Yes" --> F["Loop Terminates Cleanly"]
range(start, stop, step): Lazy sequence generator for numerical iteration.enumerate(iterable, start=0): Yields (index, item) tuples during iteration.zip(*iterables): Aggregates elements from multiple iterables in parallel.from typing import List, Tuple
def analyze_student_grades(names: List[str], scores: List[int]) -> None:
# Parallel Iteration via zip() and enumerate()
print("--- Student Grade Roster ---")
for rank, (name, score) in enumerate(zip(names, scores), start=1):
status = "Honor Roll" if score >= 90 else "Passing"
print(f"Rank {rank}: {name} - Score: {score} ({status})")
# Dictionary Key-Value Iteration
grade_map = dict(zip(names, scores))
print("
--- Iterating Dictionary Items ---")
for student, score in grade_map.items():
print(f"Student: {student:<10} | Score: {score}")
if __name__ == "__main__":
student_names = ["Alice", "Bob", "Charlie"]
student_scores = [95, 82, 88]
analyze_student_grades(student_names, student_scores)
range(len(seq)): Instead of for i in range(len(items)): print(items[i]), use for item in items: or for i, item in enumerate(items):.zip(..., strict=True) in Python 3.10+: Prevents silent truncation when zipping iterables of unequal length.for...else Construct: The else block executes only if the loop completes without hitting a break statement.Write a loop using enumerate() over ['a', 'b', 'c', 'd'] that prints the 1-based index and uppercase value for every element.
Sign in to track your learning journey, earn industry-recognized certificates, and join our elite developer community.
Quick Access With
You've completed this section! Take a quick 5-question quiz to check your understanding.