getsizeof Sizes One Object, Not Its Contents
getsizeof reports one object's own bytes including its header, excluding referenced contents — the nested-container test shows outer lists store pointers.
Code
import sys
# getsizeof reports ONE object's own storage in bytes — the container header
# included, but referenced contents excluded
print("empty list:", sys.getsizeof([]))
print("list of 1000:", sys.getsizeof(list(range(1000))))
print("empty dict:", sys.getsizeof({}))
print("dict with 1000 keys:", sys.getsizeof({i: i for i in range(1000)}))
# The same rule holds for strings and tuples
print("empty string:", sys.getsizeof(""))
print("1000-char string:", sys.getsizeof("x" * 1000))
# Nesting proves the exclusion: the outer list only stores two pointers,
# while the children it references account for almost all real memory
nested = [list(range(1000)), list(range(1000))]
outer = sys.getsizeof(nested)
children = sys.getsizeof(nested[0]) + sys.getsizeof(nested[1])
print("outer list bytes:", outer, "| referenced children bytes:", children)
print("outer is a tiny fraction:", outer < children / 10)Output
Captured from a sandboxed run of this snippet in the build pipeline.
empty list: 56
list of 1000: 8056
empty dict: 64
dict with 1000 keys: 36952
empty string: 49
1000-char string: 1049
outer list bytes: 72 | referenced children bytes: 16112
outer is a tiny fraction: TrueThe behavior laid bare
The file’s state is a handful of top-level bindings: nested, outer, children.
Putting it to use
The run emits 8 labeled sections — empty list:, list of 1000:, empty dict:, dict with 1000 keys:, empty string:, 1000-char string:, outer list bytes:, outer is a tiny fraction: — one per step.
Interactive Tools for This Topic
Kubernetes Resource CalculatorCalculate per-pod and cluster CPU and memory requests, limits, QoS class, overcommit ratios, headroom, and node fit estimates for Kubernetes workloads.SRI Hash GeneratorGenerate Subresource Integrity (SRI) hashes from resource content using SHA-256, SHA-384, or SHA-512, and copy a ready-to-use script tag.
FAQ
- Does this require external packages?
- No. It relies only on built-in language and platform APIs, so you can paste it into a project without installing anything. Every import resolves inside the standard library — `sys`. Its state lives in module-level bindings: `nested`, `outer`, `children`.
Report a problem with this exampleOpens a pre-filled issue on GitHub.