Python for JS Devs · Reference

Python syntax — JS → Python

The fast translation table. Everything a JS dev looks up in week one.

Basics

ConceptJavaScriptPython
Declare varconst x = 1x = 1
Nullnull / undefinedNone
Booleanstrue / falseTrue / False
Blockbraces { }indentation + :
Comment// ...# ...
Template string`hi ${n}`f"hi {n}"
Logic ops&& · || · !and · or · not
Equality===== (value); is (identity)
Null-coalescea ?? ba if a is not None else b
Ternaryc ? a : ba if c else b
Division7 / 2 → 3.57 / 2 → 3.5; 7 // 2 → 3
Power2 ** 102 ** 10

Collections

OpJavaScriptPython
Array / list[1, 2][1, 2]
Pushxs.push(3)xs.append(3)
Lengthxs.lengthlen(xs)
Containsxs.includes(3)3 in xs
Slicexs.slice(1,3)xs[1:3]
Last itemxs.at(-1)xs[-1]
Map/object{a: 1}{"a": 1}
Get keyo.a / o["a"]o["a"] (KeyError!) / o.get("a")
KeysObject.keys(o)o.keys()
EntriesObject.entries(o)o.items()
Setnew Set([1,2]){1, 2} (empty: set())
Tuple— (frozen array)(1, 2)
Destructure[a, b] = arra, b = arr
Spreadfn(...arr)fn(*arr); dict: fn(**d)

Control flow & comprehensions

OpJavaScriptPython
For-eachfor (const x of xs)for x in xs:
Rangefor(i=0;i<3;i++)for i in range(3):
Index+valuexs.forEach((x,i)=>)for i, x in enumerate(xs):
Zipa.map((x,i)=>[x,b[i]])zip(a, b)
Mapxs.map(f)[f(x) for x in xs]
Filter+mapxs.filter(g).map(f)[f(x) for x in xs if g(x)]
Dict buildObject.fromEntries(..){k: v for k, v in pairs}
Switchswitch(x){}match x: / case _:

Functions, classes, errors, async

OpJavaScriptPython
Functionfunction f(a){}def f(a):
Arrow/lambdax => x+1lambda x: x+1
Default argf(a, b=2)def f(a, b=2): (no mutable defaults!)
Rest args(...args)(*args, **kwargs)
Classclass C {}class C:
Constructorconstructor()def __init__(self):
thisthis.xself.x
New instancenew C()C()
Import namedimport {a} from "m"from m import a
Import moduleimport * as mimport m
Throwthrow new Error()raise ValueError()
Try/catchtry{}catch(e){}try: / except X as e:
Async fnasync functionasync def
Await allPromise.all([..])asyncio.gather(..)
Top 3 gotchas Empty []/{} are falsy in Python · missing dict key raises (use .get()) · never use a mutable default arg (def f(x=[])).