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 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

JavaScriptPython
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

JavaScriptPython
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

JavaScriptPython
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

JavaScriptPython
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

JavaScriptPython
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

JavaScriptPython
a[i] = ea[i] = e
a.splice(i, 3, e0, e1, e2)a[i:i+3] = [e0, e1, e2]

Filtering

JavaScriptPython
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

JavaScriptPython
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) + begina.index(e, begin, end)

Inclusion/Exclusion

JavaScriptPython
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

JavaScriptPython
a.join(s) // s is a strings.join(a)
a.toString()','.join(a)

Misc

JavaScriptPython
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