Whenever I鈥檓 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 and a1 refer to a JavaScript array or a Python list.
  • i, begin, end are integers that refer to some element indices.
  • e and eN 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)] or
list(filter(f, a))
a.filter(f) // f(e, i) [e for i, e in enumerate(a) if f(e, i)]

Lookup

JavaScript Python
a.find(f) next(filter(f, a)) or
next(e for e in a if f(e))
a.findLast(f) next(e for e in reversed(a) if f(e))
a.indexOf(e) a.index(e)
a.indexOf(e, begin) a.index(e, begin)
a.slice(begin, end).indexOf(e) + begin a.index(e, begin, end)

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)

Misc

JavaScript Python
a.flat() list(itertools.chain.from_iterable(a)) if a is an iterable of lists
a.reverse() a.reverse()
a.sort() a.sort()
a.sort(f) a.sort(key=functools.cmp_to_key(f))
a.sort((a, b) => (f(a) - f(b))) a.sort(key=f) # f returns a number