Python for JS Devs · Reference
Python syntax — JS → Python
The fast translation table. Everything a JS dev looks up in week one.
Basics
| Concept | JavaScript | Python |
| Declare var | const x = 1 | x = 1 |
| Null | null / undefined | None |
| Booleans | true / false | True / False |
| Block | braces { } | indentation + : |
| Comment | // ... | # ... |
| Template string | `hi ${n}` | f"hi {n}" |
| Logic ops | && · || · ! | and · or · not |
| Equality | === | == (value); is (identity) |
| Null-coalesce | a ?? b | a if a is not None else b |
| Ternary | c ? a : b | a if c else b |
| Division | 7 / 2 → 3.5 | 7 / 2 → 3.5; 7 // 2 → 3 |
| Power | 2 ** 10 | 2 ** 10 |
Collections
| Op | JavaScript | Python |
| Array / list | [1, 2] | [1, 2] |
| Push | xs.push(3) | xs.append(3) |
| Length | xs.length | len(xs) |
| Contains | xs.includes(3) | 3 in xs |
| Slice | xs.slice(1,3) | xs[1:3] |
| Last item | xs.at(-1) | xs[-1] |
| Map/object | {a: 1} | {"a": 1} |
| Get key | o.a / o["a"] | o["a"] (KeyError!) / o.get("a") |
| Keys | Object.keys(o) | o.keys() |
| Entries | Object.entries(o) | o.items() |
| Set | new Set([1,2]) | {1, 2} (empty: set()) |
| Tuple | — (frozen array) | (1, 2) |
| Destructure | [a, b] = arr | a, b = arr |
| Spread | fn(...arr) | fn(*arr); dict: fn(**d) |
Control flow & comprehensions
| Op | JavaScript | Python |
| For-each | for (const x of xs) | for x in xs: |
| Range | for(i=0;i<3;i++) | for i in range(3): |
| Index+value | xs.forEach((x,i)=>) | for i, x in enumerate(xs): |
| Zip | a.map((x,i)=>[x,b[i]]) | zip(a, b) |
| Map | xs.map(f) | [f(x) for x in xs] |
| Filter+map | xs.filter(g).map(f) | [f(x) for x in xs if g(x)] |
| Dict build | Object.fromEntries(..) | {k: v for k, v in pairs} |
| Switch | switch(x){} | match x: / case _: |
Functions, classes, errors, async
| Op | JavaScript | Python |
| Function | function f(a){} | def f(a): |
| Arrow/lambda | x => x+1 | lambda x: x+1 |
| Default arg | f(a, b=2) | def f(a, b=2): (no mutable defaults!) |
| Rest args | (...args) | (*args, **kwargs) |
| Class | class C {} | class C: |
| Constructor | constructor() | def __init__(self): |
| this | this.x | self.x |
| New instance | new C() | C() |
| Import named | import {a} from "m" | from m import a |
| Import module | import * as m | import m |
| Throw | throw new Error() | raise ValueError() |
| Try/catch | try{}catch(e){} | try: / except X as e: |
| Async fn | async function | async def |
| Await all | Promise.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=[])).