list_capacity.py

#!/usr/bin/python3
# ===================================================================
# demo the number of elements in a list vs the capacity of a list
#
# adding an element to a list does not allocatte space for one
# element at a time. rather space is allocated in chunks using
# a sliding scale.
# Notes:
# 1. a list has 56 bytes of overhead in it's data structure
# 2. getsizeof returns the number of bytes allociated to a list
# ===================================================================

import sys

# ---- number of slots available in a list
# ---- (some are used and some are not)

def list_capacity(lst:list):
    return (sys.getsizeof(lst) - 56) // 8

# ---- test/display list capacity vs elements actually in the list

def test_list_capacity():
    lst = []
    for i in range(20):
        print(f'[{i:03}] len={len(lst):<3} capacity={list_capacity(lst)}')
        lst.append(i)

# ---- main

test_list_capacity()