Types and memory

Published

2023-07-31

Types and memory

The details of how Python stores objects in memory is outside the scope of this text. Nevertheless, a little peek can be instructive.

Figure 1: A sneak peek into an int object

Figure 1 includes a representation of an integer with value (decimal) 65. In binary, decimal 65 is represented as 01000001. That’s

0 \times 2^7 + 1 \times 2^6 + 0 \times 2^5 + 0 \times 2^4 + 0 \times 2^3 + 0 \times 2^2 + 0 \times 2^1 + 1 \times 2^0

Find 01000001 within the bitstring1 shown in Figure 1. That’s the integer value.2

Figure 2 shows the representation of the string 'A'.3 The letter ‘A’ is represented with the value (code point) of 65.

Figure 2: A sneak peek into a str object

Again, find 01000001 within the bitstring Figure 2—that’s the encoding of 'A'.

Apart from both representations containing the value 65 (01000001), notice how different the representations of an integer and a string are! How does Python know to interpret one as an integer and the other as a string? The type information is encoded in this representation (that’s a part of what all the other ones and zeros are). That’s how Python knows. That’s one reason types are crucial!

Note: Other languages do this differently, and the representations (above) will vary somewhat depending on your machine’s architecture.

Now, you don’t need to know all the details of how Python uses your computer’s memory in order to write effective programs, but this should give you a little insight into one reason why we need types. What’s important for you as a programmer is to understand that different types have different behaviors. There are things that you can do with an integer that you can’t do with a string, and vice versa (and that’s a good thing).

Original author: Clayton Cafiero < [given name] DOT [surname] AT uvm DOT edu >

No generative AI was used in producing this material. This was written the old-fashioned way.

This material is for free use under either the GNU Free Documentation License or the Creative Commons Attribution-ShareAlike 3.0 United States License (take your pick).

Footnotes

  1. A bitstring is just a sequence of zeros and ones.↩︎

  2. Actually, the value is stored in two bytes 01000001 00000000 as shown within the box in Figure 1. This layout in memory will vary with the particular implementation on your machine.↩︎

  3. Python uses Unicode encoding for strings. For reading on character encodings, don’t miss Joel Spolsky’s “The Absolute Minimum Every Software Developer Absolutely, Positively Must Know About Unicode and Character Sets (No Excuses!)”.↩︎