Built-ins that save you
Part of the free LogicWiz Python course, Module 12: Iteration and the standard toolkit. The examples and practice run in the app.
Aarav wrote 14 lines with three counters and two ifs to build the class rank list. Meher did it in three, using zip, sorted and enumerate. These built-ins are always there, no import needed.
You'll learn to
- Loop with positions using `enumerate`, and in parallel using `zip`
- Check many conditions at once with `any` and `all`
- Sort and pick with `key=`, and use stable sort for tie-breaking
- Use `map`, `filter`, `reduce` and `divmod` where they help
Learn
enumerate and zip
names = ["Riya", "Kabir", "Sneha"]
marks = [91, 78, 85]
for rank, name in enumerate(names, start=1):
print(rank, name)
for name, m in zip(names, marks):
print(f"{name}: {m}")
print(dict(zip(names, marks)))
print(list(zip([1, 2, 3], "ab"))) # stops at the shorter one
No more for i in range(len(names)). zip stops quietly at the shortest input; zip(a, b, strict=True) raises an error if the lengths differ.
any and all
orders = [
{"item": "chai", "paid": True},
{"item": "dosa", "paid": False},
{"item": "vada", "paid": True},
]
print(all(o["paid"] for o in orders)) # every order paid?
print(any(o["paid"] for o in orders)) # at least one paid?
marks = [45, 82, 28]
print("someone failed" if any(m < 33 for m in marks) else "all passed")
Both stop as soon as the answer is known: any at the first True, all at the first False.
min, max and sorted with key
students = [("Riya", 91), ("Kabir", 78), ("Sneha", 91), ("Aarav", 85)]
print(max(students, key=lambda s: s[1]))
print(sorted(students, key=lambda s: s[1], reverse=True))
print(sorted(students, key=lambda s: (-s[1], s[0])))
menu = {"samosa": 15, "chai": 10, "thali": 90}
print(min(menu, key=menu.get))
Stable sort: ties keep their order
Python's sort is stable: items that compare equal stay in the order they were in.
In the example above, Riya and Sneha both have 91. Sorting by marks alone keeps Riya first, because she was first in the list.
To break ties your way, sort by a tuple key: key=lambda s: (-s[1], s[0]) means marks high to low, then name A to Z. The minus sign flips the order of a number.
map, filter and reduce
from functools import reduce
prices = list(map(int, "15 10 20 35".split()))
print(prices)
print(list(filter(lambda p: p >= 20, prices)))
print(reduce(lambda a, b: a + b, prices))
# The same with comprehensions and sum:
print([p for p in prices if p >= 20], sum(prices))
map(int, input().split()) is the classic way to read many numbers in one line. For anything more, a comprehension is usually clearer.
divmod: quotient and remainder together
minutes = 135
hours, mins = divmod(minutes, 60)
print(f"{hours}h {mins:02d}m")
amount = 1780
notes_500, rest = divmod(amount, 500)
notes_100, rest = divmod(rest, 100)
print(notes_500, "x Rs 500,", notes_100, "x Rs 100, Rs", rest, "left")
map, filter, zip and enumerate return lazy iterators, like generators. print(map(int, ['1'])) shows <map object at …>, not the numbers; wrap it in list() to see them. And like generators, they can be used only once.
University papers ask "explain map, filter and reduce with an example" (AKTU, VTU, IITM). Interviewers ask "sort() vs sorted()" and "sort students by marks, then by name": the answer is a tuple key.
In one line
enumerate for positions, zip for parallel lists (stops at the shortest), any/all for conditions, key= for sorting (stable, use a tuple for ties), divmod for quotient and remainder.
Interview corner
What is the difference between sort() and sorted()?
list.sort() sorts the list in place and returns None; it only exists on lists. sorted(iterable) works on any iterable and returns a new list, leaving the original unchanged. Both take key= and reverse=, and both are stable (Timsort, O(n log n)).
How do you sort by one field descending and another ascending?
Use a tuple key and negate the numeric field: sorted(students, key=lambda s: (-s.marks, s.name)). For a non-numeric field you can rely on stability instead: sort by the secondary key first, then by the primary key with reverse=True.
What do map, filter and reduce do? Are they still used?
map(f, it) applies f to every item; filter(f, it) keeps the items where f is truthy; functools.reduce(f, it) folds items into one value. map and filter return lazy iterators. In modern Python, comprehensions and sum/max are usually preferred for readability, but map(int, input().split()) is still everywhere.
What happens if you zip lists of different lengths?
zip stops at the shortest input and silently drops the rest. Use zip(a, b, strict=True) (Python 3.10+) to raise a ValueError on a mismatch, or itertools.zip_longest to pad the shorter one with a fill value.