From charlesreid1

Compact arrays:

To save space when implementing integer or double arrays, don't make them referential arrays. This can use 4-5 times more space. Instead, use compact arrays, from the arrays submodule. This requires specifying the type of the array.

primes = array('i', [2,3,57,11,13,17,19])

Valid codes:

  • b signed char 1 bit
  • B unsigned char 1 bit
  • u unicode char 2 bit or 4 bit
  • h signed short int 2 bit
  • H unsigned short int 2 bit
  • i signed int 2 or 4 bit
  • I unsigned int 2 or 4 bit
  • l signed long int 4 bit
  • L unsigned long int 4 bit
  • f float 4 bit
  • d float 8 bit

This only works with the built-in types mentioned above. User-defined data types cannot be used with compact arrays.

Compact arrays of such structures should be created with lower-level support of module called ctypes.

The Code

import sys
from array import array

"""
Goodrich et al
Data Structures in Python
Chapter 5: Array-Based Sequences

Exploring the use of compact arrays.
"""

n = int(1E3)
slow = [j for j in range(n)]
fast = array('i',[j for j in range(n)])
for i,j in zip(["list","array"],[slow,fast]):
    print("Size of {0} with {1} elements: {2:4d}".format(i,n,sys.getsizeof(j)))

The Output

$ python arraytype.py
Size of list with 1000 elements: 9032
Size of array with 1000 elements: 4056