Basic types

ℹ️

TypeShort descriptionMutableExample

NoneType

"Empty" value

No

None

bool

Boolean value (True or False)

No

True

int

Integer numbers

No

42

float

Floating point number

No

23.43

str

Textual data - sequense of characters

No

"Hello!"

list

Mutable sequense of any kind of objects

Yes

[1, 2, 3]

tuple

Immutable sequense of objects

No

(1, 2, 3)

set

Mutable collection of unique objects

Yes

{1, 2, 3}

frozenset

Immutable collection of unique objects

No

frozenset({1, 2, 3})

dict

The collection of key-value pairs

Yes

{"name": "Johnny", "second_name": "Walker"}

Main categories:

  • Mutable or Immutable

    • Is object allowing it's change after creation?

  • Hashable

    • Can this object be used as the key for the dictionary (has defined __hash__() and __eq__() methods)?

  • Container, sequence, iterable

    • Has this object contained elements like other objects (has methods like __iter__ or __getitem__())?

  • Callable

    • Can be invoked/run like a function or class (has method __call__() defined)?

Additional types:

  • range

  • function

  • code object

  • module

  • iterator

  • generator

  • slice object

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 requirement to store elements of int type in a different collections.

For 1 million of elements:

TypeBytes per element

Tuple

8

List

9

Set

33

Dictionary

42

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 │
└───────┴────────────┴──────────────────┘

Last updated