Perfect follow-up 👍
Let’s do this systematically + interview-ready, exactly the way you like:
🔁 Looping in Python — All Data Structures
(Ways · Patterns · Templates · Real Examples · Interview Notes)
Python loops work on iterables.
Each data structure exposes a different iteration behavior.
🧠 Big Picture (Mental Model)
Iterable ──▶ Iterator ──▶ __next__() ──▶ value
| Data Structure | What you loop over by default |
|---|---|
str | characters |
list | elements |
tuple | elements |
set | elements (unordered) |
dict | keys |
range | numbers |
zip | tuples |
enumerate | (index, value) |
1️⃣ Looping Over String
Template
for char in string:
...
With index
for i, ch in enumerate("python"):
print(i, ch)
Use case
- Parsing
- Validation
- Tokenization
📌 Immutable → read-only loop
2️⃣ Looping Over List
Template
for item in list_:
...
Index-based
for i in range(len(lst)):
print(i, lst[i])
Pythonic (recommended)
for i, item in enumerate(lst):
print(i, item)
Modify while looping ❌ (danger)
# ❌ Don't do this
for x in lst:
lst.remove(x)
Safe way
lst = [x for x in lst if x > 0]
3️⃣ Looping Over Tuple
Same as list, but immutable
Template
for item in tpl:
...
Tuple unpacking
points = [(1, 2), (3, 4)]
for x, y in points:
print(x, y)
📌 Faster than list (slightly)
📌 Safe for read-only data
4️⃣ Looping Over Set
⚠️ Unordered
Template
for item in my_set:
...
Example
emails = {"a@gmail.com", "b@gmail.com"}
for email in emails:
print(email)
📌 Use when:
- Uniqueness matters
- Order doesn’t
5️⃣ Looping Over Dictionary (VERY IMPORTANT)
5.1 Default (keys)
for key in my_dict:
print(key)
5.2 Keys explicitly
for key in my_dict.keys():
print(key)
5.3 Values
for value in my_dict.values():
print(value)
5.4 Key + Value (🔥 MOST USED)
for key, value in my_dict.items():
print(key, value)
📌 Interview note:
Dict iteration is O(n) and preserves insertion order (Python 3.7+)
6️⃣ Looping Over range()
Template
for i in range(start, stop, step):
...
Examples
for i in range(5):
print(i)
for i in range(10, 0, -1):
print(i)
📌 range is lazy (no memory waste)
7️⃣ Looping with zip()
Parallel iteration
names = ["A", "B"]
scores = [90, 80]
for n, s in zip(names, scores):
print(n, s)
📌 Stops at shortest iterable
8️⃣ Looping with enumerate()
Template
for index, value in enumerate(iterable, start=0):
...
Example
for i, ch in enumerate("data", 1):
print(i, ch)
📌 Cleaner than range(len())
9️⃣ Nested Loops (All Structures)
Matrix (List of Lists)
matrix = [[1, 2], [3, 4]]
for row in matrix:
for val in row:
print(val)
Dict of Lists
data = {"a": [1, 2], "b": [3]}
for k, values in data.items():
for v in values:
print(k, v)
🔟 Loop Control Keywords
break
for x in data:
if x == 5:
break
continue
for x in data:
if x < 0:
continue
else with loop (INTERVIEW FAVORITE ⭐)
for x in data:
if x == 10:
break
else:
print("Not found")
🧩 Universal Loop Templates (SAVE THESE)
1️⃣ Read-only traversal
for item in iterable:
process(item)
2️⃣ Index-aware
for i, item in enumerate(iterable):
process(i, item)
3️⃣ Filtered loop
for item in iterable:
if condition(item):
process(item)
4️⃣ Parallel loop
for a, b in zip(it1, it2):
process(a, b)
5️⃣ Dict processing
for k, v in dict_.items():
process(k, v)
⚠️ Common Mistakes (Interview Traps)
❌ Modifying list while looping
❌ Assuming set order
❌ Using range(len()) unnecessarily
❌ Forgetting .items() for dict key-value loop
🎯 Final Summary Table
| Structure | Best Loop Style |
|---|---|
| String | for ch in s |
| List | for i, x in enumerate(lst) |
| Tuple | for x in tpl |
| Set | for x in set_ |
| Dict | for k, v in dict.items() |
| Parallel | zip() |
| Index + Value | enumerate() |
If you want next:
- 🔬 Behind-the-scenes iterator protocol
- ⚡ Loop performance & Big-O
- 🧠 Loop → comprehension transformation
- 🎯 20 tricky interview questions
Just say continue 🚀