Difficulty: Beginner
Python provides several advanced techniques to make loops more powerful and concise. Mastering these techniques is what separates beginner Python code from professional-grade code.
The `zip()` function takes two or more iterables and combines them element-wise into tuples. It stops at the shortest iterable by default. This is invaluable when you need to iterate over multiple sequences in parallel without using index-based access.
List comprehensions provide a compact syntax for creating new lists by transforming and filtering elements from an existing iterable. The syntax is `[expression for item in iterable if condition]`. They are faster than equivalent for loops because they are optimized at the C level in CPython.
Python has a unique feature: an `else` clause on loops. The else block after a for or while loop executes only if the loop completed normally (without hitting a break). This is useful for search patterns where you want to take action when a target is not found.
These techniques are heavily tested in interviews because they demonstrate a deep understanding of Python's iteration protocol and the ability to write clean, idiomatic code.
names = ["Alice", "Bob", "Carol"]
scores = [92, 85, 78]
grades = ["A", "B", "C+"]
for name, score, grade in zip(names, scores, grades):
print(f"{name}: {score} ({grade})")
zip() combines three lists element by element. Each iteration unpacks one tuple of (name, score, grade). No index variable needed.
# Transform: square each number
numbers = [1, 2, 3, 4, 5]
squares = [x2 for x in numbers]
print(f"Squares: {squares}")
# Filter: only even numbers
evens = [x for x in numbers if x % 2 == 0]
print(f"Evens: {evens}")
# Transform + Filter: square only odd numbers
odd_squares = [x2 for x in numbers if x % 2 != 0]
print(f"Odd squares: {odd_squares}")
List comprehensions combine mapping and filtering in one line. The if clause is optional and filters which elements are included.
def find_prime_factor(n):
for i in range(2, n):
if n % i == 0:
print(f"{n} is divisible by {i}")
break
else:
print(f"{n} is prime")
find_prime_factor(7)
find_prime_factor(12)
find_prime_factor(13)
The else block runs only when the loop finishes without break. If break is triggered (a factor is found), the else block is skipped. This is a clean pattern for search operations.
keys = ["name", "age", "city"]
values = ["Alice", 30, "Pune"]
person = dict(zip(keys, values))
print(person)
# Unzipping with zip(*...)
pairs = [(1, "a"), (2, "b"), (3, "c")]
nums, letters = zip(*pairs)
print(f"Numbers: {nums}")
print(f"Letters: {letters}")
zip() combined with dict() is a clean way to build dictionaries from parallel lists. The zip(*iterable) pattern transposes rows and columns.
zip(), list comprehension, else clause on loops, itertools basics, Pythonic iteration