Python Data Types: Strings, Numbers, and Complex Types (vs JavaScript)

New episode of Python For JavaScript Developers, a series of side-by-side comparisons between Python and JavaScript. In this installment: Python data types.

Python For JavaScript Developers: Python Data Types

This series is a hitchhiker guide to Python for JavaScript developers, wrote as a reference while training other fellow devs, and as a note for my future self. Enjoy!

In this episode:

  • Basic data types: string, number, boolean
  • Complex data types: dictionary, list, tuple, set

Python For JavaScript Developers: requirements

To follow along you need at least a basic understanding of JavaScript and its quirks. This series is not an exhaustive guide to both languages, rather, a 10.000 feet comparison between them.

You can try the code examples for JavaScript in a browsers’s console or in the Node.js REPL. For Python you can use the Python REPL. Every time you see “>>>” in the code examples, that’s the Python REPL.

The complete series

Missed an episode? Here we go:

Basic data types in Python and JavaScript

In computer programming data types are basically “shapes” that you can work on. Most programming languages have a group of basic data types like strings, numbers, and booleans.

Python and JavaScript make no exception. Here’s an overview of the most important basic data types available on both languages (n/a stands for not applicable).

PYTHONJAVASCRIPTMUTABLE IN PYTHONMUTABLE IN JS
floatNumbernono
intBigIntnono
intn/anon/a
stringStringnono
booleanBooleannono
NoneNullnono
n/aUndefinedn/ano
n/aSymboln/ano

JavaScript has eight types, seven of which are called primitives (Object is a type on its own). You can notice from the table that both Python and JavaScript basic types are immutable. For example in Python we refer to string as an immutable sequence of unicode characters.

Like most basic types, Python strings have methods for common operations:

>>> name = "caty"

>>> name.capitalize()
>>> name.center(40)
>>> name.count("t")

## and more!

Since strings are immutable, the result of a string operation is always a new string.

And now numbers. In JavaScript there is no distinction between integers and floating point numbers, they are just a Number data type. In Python instead there are integers and floats.

JavaScript got recently a BigInt primitive type for representing very large numbers. Python instead seems to handle small and big integers with a single int type.

Would be remiss not to mention the quintessential boolean, which in Python can assume either the value of False or True.

An important note on special values. Python has None for describing an empty value. In JavaScript instead there is the dreaded null.

Also in Python there is neither the concept of undefined like in JavaScript, nor a corresponding type Symbol, a rather esoteric JavaScript primitive.

Python data types and JavaScript: immutability and variables

You may have noticed from the table above that most of the basic Python data types are immutable. JavaScript in practice seems more relaxed. Try the following examples in a browser’s console or in Node.js REPL. Numbers? Seem mutable:

var a = 34;
++a
// returns 35

Booleans? Seem mutable as well:

var x = false;
x++;
// returns 0 and x becomes 1

Null? Again, seems mutable:

var x = null;
x++;
// returns 0 and x becomes 1

Don’t get fooled. What is changing here is not the underlying primitive, but the value assigned to the variable.

The last two examples with boolean and null are a case of type coercion. The engine transforms both values to the corresponding numeric representation, and the variable gets assigned the new value.

See this example on MDN for more.

Complex data types in Python and JavaScript

A complex data types is a more sophisticated “shape” opposed to simple primitives like strings and numbers. In Python we can name list, dictionary, set, and tuple.

In JavaScript instead the distinction is slightly less noticeable because Object is the topmost complex type and other subtypes like Array and Set are just specialized versions of their “ancestor” (Function is an object too).

Here’s a breakdown of complex data types in Python and JavaScript:

PYTHONJAVASCRIPTMUTABLE IN PYTHONMUTABLE IN JS
listArrayyesyes
dictionaryObjectyesyes
setSetyesyes
tuplen/anon/a

As you can see arrays and objects in JavaScript are always mutable, and so Object. Unless you protect them with the help of external libraries, there is no way to avoid mutating objects. However, there are plans for adding immutable types to JavaScript in the future.

Python on the other hand has an immutable complex type called tuple (while list, dictionary, and set are mutable). Let’s see Python complex types in more detail.

Python data types: list and tuples

A list in Python is a collection of elements, just like JavaScript arrays. Here’s a Python list:

>>> my_list = ["vale", 98, "caty", None]

List operations always mutate the original list:

>>> my_list = ['a', None, 44, True, 'f']

>>> my_list.append(44)
>>> my_list.remove('f')

>>> print(my_list) 

# Output: ['a', None, 44, True, 44]

A tuple instead is immutable, in fact it has only two read-only operations (index and count):

>>> my_tuple = ("vale", "Italy", 105)
>>> my_tuple.count("Italy") # 1
>>> my_tuple.index(105) # 2

Notice that tuples are enclosed in round brackets.

Python data types: dictionaries and JavaScript objects

JavaScript objects are containers for key/value pairs:

var obj = {
  name: "John",
  age: 33
};

But they’re also the pillar for other specialized objects. “Almost everything in JavaScript is an object” is not just a way of saying. It is the actual truth. Array, Function, Set, and more, are just JavaScript objects.

Python has something similar called dictionary (or dict for short), but it’s just a container, not a fundamental building block:

>>> my_dict = {
    "name": "John", 
    "city": "Rome", 
    "age": 44
    }

Values from a dictionary can be accessed or changed via their key:

>>> my_dict = {
    "name": "John", 
    "city": "Rome", 
    "age": 44
    }

>>> my_dict["name"]

>>> my_dict["city"] = "Florence"

Python dictionaries are mutable, yet they support read-only operations like, .get(), .items(), or .keys():

>>> my_dict = {
    "name": "John", 
    "city": "Rome", 
    "age": 44
    }

>>> my_dict.get("name") # 'John'

>>> my_dict.keys() # ['name', 'city', 'age']

You can also remove an element from the dictionary or clear it completely with .clear():

>>> my_dict = {
    "name": "John", 
    "city": "Rome", 
    "age": 44
    }

>>> my_dict.pop("name") # returns 'John' and removes it

>>> my_dict.clear() # my_dict is empty now

List, tuple, dictionary, and set are also called collections or sequences because they hold a certain number of elements, and expose common operation for interacting with them.

Python data types: Set and JavaScript Set

JavaScript’s Set is a convenient data structure useful for storing unique values. A Set may contain primitive types (even null and undefined) or references to an object:

const mySet = new Set();

mySet.add( "aString" )
mySet.add( null )
mySet.add( NaN )
mySet.add(1)
mySet.add(1)

// Output: Set { 'aString', null, NaN, 1 }

There is no much you can do with a JavaScript Set, other than adding elements, checking their existence or looping over it. A Set has the following methods:

  • .add
  • .clear
  • .delete
  • .entries
  • .forEach
  • .has
  • .keys
  • .size
  • .values

Python’s Set works more or less the same. You can add unique elements in it or check them as well:

>>> my_set = set()
>>> my_set.add( "aString" )
>>> my_set.add( None )
>>> my_set.add( 1 )
>>> my_set.add( 2 )
>>> my_set.add( 1 )
>>> my_set

# Output: {None, 2, 'aString', 1}

However the main difference from JavaScript is that Python has more useful methods for mathematical set operations like “difference”, “intersection”, “issubset”, “issuperset”, “union”, and more.

For declaring a Set in Python there is also the literal form:

>>> my_set = { None, "caty", "venice", 84}
>>> another_set = { "and", "mouse", 44, "a" }

As you might have guessed Set in both languages is really useful for removing duplicates. And in Python can do nice things like union:

>>> my_set | another_set

# Output: {'and', 'mouse', None, 'venice', 'caty', 44, 84, 'a'}

or intersection:

>>> my_set = { None, "caty", "venice", 84, "common_element" }
>>> another_set = { "and", "mouse", 44, "a", "common_element" }
>>> my_set & another_set

# Output: {'common_element'}

Worth mentioning, a set is mutable both in JavaScript and Python, but single elements inside the set remain immutable.

Python data types: wrapping up

Python and JavaScript are not so distant when it comes to basic data types. Strings, numbers, and booleans are there for you. And when working with arithmetic or comparison operators in Python there’s no need to worry about strange conversion rules.

For complex data types Python has the convenient tuple (an immutable list) over the classic JavaScript array. Also, set, a collection of unique elements, offers more methods over JavaScript’s Set. In Python you can intersect and join sets besides other helpful mathematical operations.

Thanks for reading and stay tuned for more!

Leave a Reply

Your email address will not be published. Required fields are marked *

This site uses Akismet to reduce spam. Learn how your comment data is processed.