Whenever I’m learning or using an unfamiliar programming language, I often find that even some common tasks can become overwhelming. A quick reference table that refers back to my familiar programming language often helps me carry over tricks that I already know, at least initially.
The tables below are intended to help JavaScript/Python programmers learn and quickly find idiomatic ways to perform certain tasks on lists/arrays in Python/JavaScript.
Throughout this post:
f
refers to a function.a
anda1
refer to a JavaScript array or a Python list.i
,begin
,end
are integers that refer to some element indices.e
andeN
refer to an element.
Accessing
JavaScript | Python |
---|---|
a[i] | a[i] |
a.at(-i) | a[-i] |
a.slice() | a[:] |
a.slice(begin) | a[begin:] |
a.slice(0, end) | a[:end] |
a.slice(begin, end) | a[begin:end] |
Iterating
JavaScript | Python |
---|---|
a.forEach(f) // f(e) | for e in a: f(e) |
a.forEach(f) // f(e, i) | for i, e in enumerate(a): f(e, i) |
Mapping
JavaScript | Python |
---|---|
a.map(f) // f(e) | [f(e) for e in a] or list(map(f, a)) |
a.map(f) // f(e, i) | [f(e, i) for i, e in enumerate(a)] |
Adding Elements
JavaScript | Python |
---|---|
a.push(e) | a.append(e) |
a.unshift(e) | a.insert(0, e) |
a.splice(i, 0, e) | a.insert(i, e) |
a.concat(a1) | a + a1 |
a = a.concat(a1) | a.extend(a1) |
Removing Elements
JavaScript | Python |
---|---|
a.pop() | a.pop() |
a.shift() | a.pop(0) |
a.splice(i, 1) | a.pop(i) or del a[i] |
a.splice(i, n) | del a[i:i+n] |
Modifying Elements
JavaScript | Python |
---|---|
a[i] = e | a[i] = e |
a.splice(i, 3, e0, e1, e2) | a[i:i+3] = [e0, e1, e2] |
Filtering
JavaScript | Python |
---|---|
a.filter(f) // f(e) | [e for e in a if f(e)] orlist(filter(f, a)) |
a.filter(f) // f(e, i) | [e for i, e in enumerate(a) if f(e, i)] |
Lookup
Inclusion/Exclusion
JavaScript | Python |
---|---|
a.includes(e) | e in a |
a.some(f) | any(f(e) for e in a) |
a.every(f) | all(f(e) for e in a) |
String
JavaScript | Python |
---|---|
a.join(s) // s is a string | s.join(a) |
a.toString() | ','.join(a) |