Blog

Links

Python and JavaScript: lists and arrays

posted: May 9, 2020

tl;dr: (Python_list == JavaScript_array) is not a bad approximation...

The fourth in a series of posts highlighting the commonalities of Python and JavaScript.

Python and JavaScript have many similarities in their memory models. Both are highly object-oriented languages, in which values stored in memory are actually objects. Variable names in both languages are pointers to, or references to, or bindings to, objects that live in memory (see Time to deprecate the container model for variables). Because of this similarity in memory models, the built-in data structures in each language are very similar.

In particular, the built-in data structures in each language that allow a dynamic collection of objects to be assembled and used, the Python list and the JavaScript array, are fundamentally the same. Both are mutable data structures that allow individual elements (or items) to be added, removed, or changed. Some of the syntax is identical, and can even be cut-and-pasted from one language to the other. Recent enhancements to JavaScript have morphed JavaScript arrays to become even more like Python lists.

One big difference, however, is the name that each language uses. Being an old-school programmer who wrote lots of C language code before Python and JavaScript even were invented, when I hear the word “array” I think of a C array: a fixed block of allocated memory with all elements of the array being the same type and in contiguous memory locations. A JavaScript array is not that at all.

Instead, just as in a Python list, each element of a JavaScript array can be a different type. The elements are not contiguous but are scattered all around the memory the interpreter is managing. The size of the array/list can also dynamically grow and shrink. In computer science terminology, the word “list” is more descriptive of the structure of both Python lists and JavaScript arrays, which each have pointers to all the elements. Neither language has a built-in data type that mimics C arrays. However for Python, that is exactly what the popular data science package numpy provides: tightly packed C-style arrays of the same data type, which are optimized for speedy data analysis and mathematical computation.

The syntax for creating a JavaScript array and a Python list by setting a variable equal to a literal is identical, as is the syntax for accessing an element. Assuming that the variables a and b have previously been declared in JavaScript, the following statements work in both languages:

a = [100, 200, 300, 400]
b = a[2]

After those two statements execute, b will have the value of 300, as both languages use zero-indexing.

As we compare Python lists and JavaScript arrays further, we start to get into minor differences in syntax but not differences in behavior. In general, as befits the two languages as a whole, the Python syntax is shorter and cleaner, with fewer punctuation marks. There is a bit more powerful functionality built into Python. There are also sometimes multiple ways to do the same basic task in JavaScript, which is a legacy of its evolution.

It’s common to have to add a new element to the end of a collection, especially when first building it up. To add 500 to the end of a in JavaScript one would do a.push(500) whereas in Python is it a.append(500). The last element can be removed in both languages by doing a.pop(). Perhaps JavaScript scores a point for consistency among those two method names, although ‘append’ is a bit more descriptive because it indicates where the new element will go. To get the length of the collection, JavaScript uses a built-in property, so it is a.length, whereas Python uses a built-in function, len(a).

One of the most common programming tasks is to iterate through all elements of a collection and perform operations on each element. In old-style JavaScript the standard way of doing so was to generate an index inside of a C-style for loop, and use the index to access the element:

for (let i = 0; i < a.length; i++) {
  element = a[i];
  // do stuff with element
}

Python doesn’t have C-style for loops. It is possible to use range() to generate index values that can be used to access each element of a list, but that is not the Pythonic way of doing it. Instead, Python has a very elegant for loop:

for element in a:
    # do stuff with element

Modern JavaScript has two other ways to iterate through arrays, without generating index values. There’s the forEach() method:

a.forEach( element => {
  // do stuff with element
})

and my favorite, the nearly Pythonic for/of loop:

for (let element of a) {
  // do stuff with element
}

There are many other similarities between JavaScript arrays and Python lists, as well as some differences that can be worked around:

Concatentation

Python allows lists to be concatenated with the + operator. In JavaScript you can use the + operator to combine arrays, but it probably doesn’t do what you want or expect. Instead, JavaScript has the concat() method.

Sort method

Both Python and JavaScript have a sort() method, which will sort a list or array in place. Python’s default behavior of sort() works for both numbers and strings, whereas JavaScript’s only works for strings. Both allow a function to be passed in to specify the sorting behavior.

Slicing

Python has a powerful slice operator to access the desired elements of a list. For the example above, a[1:3] will return [200, 300]. JavaScript doesn’t have a slice operator but it does have a slice method, so a.slice(1, 3) will return the same result.

Joining strings

If you have a list/array of words:

s = ['the', 'sky', 'is', 'blue']

you can use a join() method to join them together into one string. But the two languages do joins in opposite ways. In Python, strings have a join() method that accepts a list (or other iterable), so you do:

' '.join(s)

whereas in JavaScript arrays have a join() method that accepts a string, so you do:

s.join(' ')

Arguably the Python way is slightly more consistent, because you start with a string and apply a method and end up with a string, but the JavaScript way (start with an array, apply a method, and end up with a string) may be more immediately understandable.

Comprehensions

I’m a big fan of list comprehensions in Python. Once you understand how to use them, they provide a (usually) one-line way to generate a new list by mapping or filtering, and the syntax is simpler. The run-time performance has been optimized in Python, so they can be faster than for loops. And they can be easily turned into generators via a generator expression for further performance improvements. According to documentation on Mozilla, there was an attempt to add array comprehensions to JavaScript years ago, but it failed. That’s okay, there are other ways of accomplishing the same things in JavaScript.

Tuples

Tuples are more than just immutable collections. They provide a way of building a collection that shouldn’t ever be modified. Python has tuples and JavaScript doesn’t, but it is certainly possible to program without using tuples.

There are other differences between Python lists and JavaScript arrays, but at a high level they are very similar data structures for holding collections of objects.

Previous: Dynamic and static typing

Next: Dicts and objects