Loops & IterationLesson 2 of 2
Iteration Toolkit
JS puts its iteration helpers on Array.prototype: sort, some, every, reduce, map, filter. Python puts most of them in built-in functions instead: sorted(), min(), max(), sum(), any(), all(), enumerate(), zip(), reversed(), map(), and filter(). Because they are functions rather than methods, they work on any iterable: lists, tuples, sets, dict keys, strings, files, and generators alike.
Sorting is where JS developers save the most pain. JS's default sort compares elements as strings, so [10, 9, 1].sort() gives [1, 10, 9]. Python compares numbers as numbers. And instead of a comparator like (a, b) => a.age - b.age, Python takes a key function that returns the value to sort by: sorted(users, key=lambda u: u["age"]). Add reverse=True for descending order, or return a tuple from the key to sort by several fields. Python's sort is stable, like modern JS.
min() and max() accept the same key argument, so finding the youngest user is one call: min(users, key=lambda u: u["age"]). any() and all() are Python's some() and every(), and they pair beautifully with generator expressions: any(u["age"] < 18 for u in users). sum() covers the most common use of reduce(). For everything else functools.reduce exists, but Python developers rarely reach for it.
map() and filter() exist too, but they return lazy iterators, and most Python developers prefer comprehensions for the same job. Finally, two small upgrades: enumerate(items, start=1) numbers items from 1, and zip(a, b, strict=True) (Python 3.10+) raises ValueError when the inputs have different lengths instead of silently dropping the extras.
Quick reference
| JavaScript | Python | Note |
|---|---|---|
| arr.sort((a, b) => a.age - b.age) | sorted(arr, key=lambda u: u["age"]) | Key function, returns a new list |
| [10, 9, 1].sort() → [1, 10, 9] | sorted([10, 9, 1]) → [1, 9, 10] | Numbers sort numerically |
| arr.some(x => x > 10) | any(x > 10 for x in arr) | Short-circuits |
| arr.every(x => x > 0) | all(x > 0 for x in arr) | True for empty input |
| Math.max(...arr) | max(arr) | Any iterable, supports key= |
| arr.reduce((a, b) => a + b, 0) | sum(arr) | Built-in for numbers |
| arr.toReversed() | reversed(arr) / arr[::-1] | Lazy iterator / new list |
| arr.map(fn) | map(fn, arr) | Lazy; comprehension preferred |
Side by side
// JavaScript
const users = [
{ name: "Ana", age: 31 },
{ name: "Bo", age: 25 },
{ name: "Cy", age: 42 },
];
const byAge = [...users].sort((a, b) => a.age - b.age);
const oldest = users.reduce((a, b) => (b.age > a.age ? b : a));
const anyTeen = users.some(u => u.age < 20);
const allAdults = users.every(u => u.age >= 18);
const total = users.reduce((sum, u) => sum + u.age, 0);
[10, 9, 1].sort(); // [1, 10, 9] - compared as strings!
users.forEach((u, i) => console.log(i + 1, u.name));# Python
users = [
{"name": "Ana", "age": 31},
{"name": "Bo", "age": 25},
{"name": "Cy", "age": 42},
]
by_age = sorted(users, key=lambda u: u["age"])
oldest = max(users, key=lambda u: u["age"])
any_teen = any(u["age"] < 20 for u in users)
all_adults = all(u["age"] >= 18 for u in users)
total = sum(u["age"] for u in users)
sorted([10, 9, 1]) # [1, 9, 10] - numeric!
sorted(users, key=lambda u: u["age"], reverse=True)
for i, u in enumerate(users, start=1):
print(i, u["name"])
names = ["Ana", "Bo"]
ages = [31, 25, 42]
list(zip(names, ages)) # [('Ana', 31), ('Bo', 25)] - 42 dropped!
# zip(names, ages, strict=True) -> ValueError (3.10+)
list(reversed([1, 2, 3])) # [3, 2, 1]
list(map(str.upper, names)) # ['ANA', 'BO']Exercise
Real Python, running in your browserThe products list below is already defined for you. Use built-in functions (no manual loops except for printing):
products = [
{"name": "Laptop", "price": 999, "stock": 5},
{"name": "Mouse", "price": 25, "stock": 0},
{"name": "Monitor", "price": 300, "stock": 2},
{"name": "Cable", "price": 10, "stock": 40},
]
1. by_price: products sorted by price, most expensive first
(do not modify products itself)
2. cheapest: the product dict with the lowest price (one call, no sorting)
3. any_out_of_stock: True if any product has stock 0
4. all_under_1000: True if every price is under 1000
5. inventory_value: total of price * stock across all products
6. Print a numbered list starting at 1: "1. Laptop", "2. Mouse", ...1. Laptop 2. Mouse 3. Monitor 4. Cable
Ctrl + Enter runCtrl + Shift + Enter checkTab indentEsc then Tab to leave the editorCtrl + / comment