Python for JS Devs · Fundamentals
Loops are different, and comprehensions replace half your .map()/.filter() muscle memory.
forPython's for is always "for-each". To loop over numbers you iterate a range. To get an index, you use enumerate — never manual counters.
for (let i = 0; i < 3; i++) {}
for (const x of xs) {}
xs.forEach((x, i) => {});for i in range(3): ... # 0,1,2
for x in xs: ... # for-of
for i, x in enumerate(xs): ... # index + valueTwo more you'll use daily: zip(a, b) pairs up iterables, and iterating a dict yields its keys (use .items() for pairs):
for name, score in zip(names, scores): ...
for key, value in user.items(): ...
if (a) {} else if (b) {} else {}
const label = ok ? "y" : "n";
switch (kind) { ... }if a: ...
elif b: ...
else: ...
label = "y" if ok else "n" # value-first ternary
match kind: # structural, since 3.10
case "a": ...
case _: ... # defaultX if cond else Y. And Python has no &&/||/! — it's the words and, or, not. (a or b still returns the first truthy value, like JS ||.)A comprehension builds a list/dict/set in one expression. It replaces most .map() and .filter() chains, and idiomatic Python strongly prefers it.
xs.map(x => x * 2)
xs.filter(x => x > 0)
.map(x => x * 2)
Object.fromEntries(
pairs.map(([k,v]) => [k, v*2]))[x * 2 for x in xs]
[x * 2 for x in xs if x > 0]
# filter + map in one pass
{k: v * 2 for k, v in pairs}
# dict comprehensionThe mental template: [ expression for item in iterable if condition ]. Swap the brackets for {} to get a set or (with k: v) a dict comprehension.
for loop — don't abuse a comprehension for its effect. And if it needs two ifs and a nested loop, a normal loop is more readable.
Given nums = [5, -2, 8, -1, 3], in the REPL write a single comprehension that squares only the positive numbers → [25, 64, 9]. Then rewrite label = "pass" if score >= 50 else "fail" for a score you pick. Nailing the comprehension template is the win.
for i, x in enumerate(xs) is the idiom — never a manual counter.A if cond else B..filter().map() is:[f(x) for x in xs if cond] does filter+map in one readable pass — the Pythonic choice.(x for x in xs) better than a list comprehension? Worth asking before Lesson 10.