Python Lists vs Array.array() Memory Usage Compared

Here's an interesting thing I came to know about Python today (which I should have known earlier, but anyway): Python can store all kinds of data types within a list or tuple is because it just stores the reference of the elements. Where as if you use something like array.array(), it will store the actual values, and hence, you will be able to store only one kind of data type in that. And as an inference, array.array() takes very less memory, since it has only the values, while a list on its whole (if you include memories of all the references it carries) takes more memory. For example, I just created a list of 10 million ints, and an array.array() of the same and ran a test, with Python 3.14 interpreter, and here's the result: Size of array.array for 10 million ints: 39.07MB Size of list for 10 million ints: 390.14MB Further more: Sequences like lists, tuples are called "container sequence" as they contain multiple objects. Sequences like array.array() are called "flat sequence" as they contain only values. The below image is taken from "Fluent Python" book, written by Luciano Ramalho, and it explains diagrammatically about Container sequence and Flat sequence. #python

  • diagram

To view or add a comment, sign in

Explore content categories