What CPython Does With Your Objects

A Python-first developer interview rarely stops at a correct solution. The follow-up questions ask what the language does underneath: why a loop is slow, why a list uses so much memory, or what a short snippet prints. Almost every answer comes from two facts about CPython, the standard implementation. Every value is an object on the heap, and every name is a reference to one.

Every value is an object

In CPython, an integer is not a machine word. It is a heap object with a header that holds a reference count and a pointer to its type, followed by the value. sys.getsizeof(1) is 28 bytes on a 64-bit build, and a float takes 24.

A list does not hold values either. It holds pointers to objects, 8 bytes per slot. A list of a million distinct floats is therefore 8 MB of pointers plus a million 24-byte float objects, over 30 MB in total. A numpy float64 array holds the same numbers as raw doubles in 8 MB, next to each other in memory.

The rest of this lesson is for subscribers

Unlock every lesson in Programming for Quantitative Developers, and every other premium course.

Subscribe to continue

Test your knowledge

Questions are only available to subscribers.

Keep reading Programming for Quantitative Developers

33 lessons in this course, and every other premium course, on one subscription.

  • Every lesson in every course, with the worked examples and interactive simulators
  • Graded questions on every lesson, with explanations for the wrong answers as well as the right one
  • The trainers, timed assessments and brainteaser library that go with them