Python Control Flow
Python For Loops
A for loop lets you go through the items of a sequence — like a list, string or dictionary — one by one, running the same block of code for each item.
for-in Syntax
A for loop uses the pattern for item in sequence:, where sequence can be any iterable such as a list, tuple, string or range. On each pass, item takes the value of the next element automatically — no manual counter needed.
fruits = ["apple", "banana", "cherry"]
for fruit in fruits:
print(fruit)Iterating Over a String
Since a string is a sequence of characters, a for loop visits each character in turn.
for letter in "Python":
print(letter)Iterating Over a Dictionary
Looping directly over a dictionary gives you its keys. To get both key and value together, call the .items() method, which is the most common pattern when working with dictionaries.
student = {"name": "Priya", "age": 21, "city": "Pune"}
for key, value in student.items():
print(key, "->", value)Getting the Index with enumerate()
When you need both the position and the value while looping, wrap your sequence with enumerate(). It returns pairs of (index, item), starting from 0 by default, which is far cleaner than managing a separate counter.
colors = ["red", "green", "blue"]
for index, color in enumerate(colors):
print(index, color)The for-else Clause
Just like while, a for loop can have an else block that runs only when the loop completes without hitting a break. This is useful for search patterns where you want to know a match was never found.
numbers = [2, 4, 6, 8]
for n in numbers:
if n % 2 != 0:
print("Found an odd number")
break
else:
print("All numbers are even")| You want to loop over | Example |
|---|---|
| A list | for item in my_list: |
| A string | for ch in "hello": |
| A dict (keys + values) | for k, v in d.items(): |
| A range of numbers | for i in range(5): |
Use enumerate() instead of range(len(sequence)) — it is more readable and avoids off-by-one indexing mistakes.
