for — Intermediate Examples
Starts a loop that iterates over a sequence or iterable
List comprehensions
Concise syntax for building lists from loops.
python
# Basic comprehension squares = [x**2 for x in range(10)] print(squares) # With filter evens = [x for x in range(20) if x % 2 == 0] print(evens) # Nested comprehension (matrix) matrix = [[i * j for j in range(1, 4)] for i in range(1, 4)] for row in matrix: print(row) # Dict comprehension word = "mississippi" freq = {ch: word.count(ch) for ch in set(word)} print(freq)
Comprehensions are syntactic sugar for common for-loop-and-append patterns. They are often faster because the append is optimized internally.
Iterating over dictionaries
Different ways to loop over dict keys, values, and items.
python
scores = {"Alice": 95, "Bob": 87, "Charlie": 92}
# Keys (default)
for name in scores:
print(name)
# Values
for score in scores.values():
print(score)
# Items (key-value pairs)
for name, score in scores.items():
print(f"{name}: {score}")
# Sorted iteration
for name in sorted(scores, key=scores.get, reverse=True):
print(f"{name}: {scores[name]}")Iterating over a dict yields keys by default. Use .values() for values, .items() for key-value pairs, and sorted() for ordered iteration.
Want to try these examples interactively?
Open Intermediate Playground