And much more (because everything in Python is a object and thus - everything is of some specific type).
Sizes of the object of basic types:
import sys, rich
table = rich.table.Table(rich.table.Column(header="Object", style="blue"),
"Type",
rich.table.Column(header="Size", style="cyan", justify="right"),
title="Basic types memory usage", show_lines=True)
objects = [ None, True, 42, 3.1415, "Hello", [1, 2, 3], ("a", "b", "c"),
{1, 2, 3}, frozenset({1, 2, 3}), {"x": 1, "y": 2} ]
for obj in objects:
table.add_row(*map(str, (obj, type(obj), sys.getsizeof(obj))))
rich.console.Console().print(table)
Basic types memory usage
┏━━━━━━━━━━━━━━━━━━━━━━┳━━━━━━━━━━━━━━━━━━━━━┳━━━━━━┓
┃ Object ┃ Type ┃ Size ┃
┡━━━━━━━━━━━━━━━━━━━━━━╇━━━━━━━━━━━━━━━━━━━━━╇━━━━━━┩
│ None │ <class 'NoneType'> │ 16 │
├──────────────────────┼─────────────────────┼──────┤
│ True │ <class 'bool'> │ 28 │
├──────────────────────┼─────────────────────┼──────┤
│ 42 │ <class 'int'> │ 28 │
├──────────────────────┼─────────────────────┼──────┤
│ 3.1415 │ <class 'float'> │ 24 │
├──────────────────────┼─────────────────────┼──────┤
│ Hello │ <class 'str'> │ 54 │
├──────────────────────┼─────────────────────┼──────┤
│ [1, 2, 3] │ <class 'list'> │ 80 │
├──────────────────────┼─────────────────────┼──────┤
│ ('a', 'b', 'c') │ <class 'tuple'> │ 64 │
├──────────────────────┼─────────────────────┼──────┤
│ {1, 2, 3} │ <class 'set'> │ 216 │
├──────────────────────┼─────────────────────┼──────┤
│ frozenset({1, 2, 3}) │ <class 'frozenset'> │ 216 │
├──────────────────────┼─────────────────────┼──────┤
│ {'x': 1, 'y': 2} │ <class 'dict'> │ 232 │
└──────────────────────┴─────────────────────┴──────┘
Memory size may not be the only criteria to select data type. Rather, time required to perform operation on data type can be critical criteria.
import sys, rich
n = 1000000
tests = {
"list": [*range(n)],
"tuple": tuple(range(n)),
"set": set(range(n)),
"dict": dict.fromkeys(range(n))
}
table = rich.table.Table("Type",
rich.table.Column(header="Total size", style="cyan", justify="right"),
rich.table.Column(header="Size per element", style="red", justify="right"),
title=f"Collections memory requirement ({n} elements)", show_lines=True
)
for type_, collection in tests.items():
# print(f"Size of <{type_}> ({n} items): {sys.getsizeof(collection)}, {sys.getsizeof(collection) / n} per element")
table.add_row(str(type_), str(sys.getsizeof(collection)), str(sys.getsizeof(collection) / n))
rich.console.Console().print(table)
Collections memory requirement (1000000
elements)
┏━━━━━━━┳━━━━━━━━━━━━┳━━━━━━━━━━━━━━━━━━┓
┃ Type ┃ Total size ┃ Size per element ┃
┡━━━━━━━╇━━━━━━━━━━━━╇━━━━━━━━━━━━━━━━━━┩
│ list │ 8000056 │ 8.000056 │
├───────┼────────────┼──────────────────┤
│ tuple │ 8000040 │ 8.00004 │
├───────┼────────────┼──────────────────┤
│ set │ 33554648 │ 33.554648 │
├───────┼────────────┼──────────────────┤
│ dict │ 41943136 │ 41.943136 │
└───────┴────────────┴──────────────────┘