Python
Programming
Object-Oriented Programming
Python Coding
Size Determination

How do I determine the size of an object in Python?

Master System Design with Codemia

Enhance your system design skills with over 120 practice problems, detailed solutions, and hands-on exercises.

Introduction

In Python, object size is useful when you are investigating memory growth, comparing data structures, or trying to understand why a process uses more RAM than expected. The important detail is that Python can tell you the size of an object itself, but that number is often different from the total memory retained by everything the object references.

Start With sys.getsizeof

The standard tool is sys.getsizeof. It reports the immediate size of one object in bytes, including Python's own overhead for that object.

python
1import sys
2
3number = 42
4text = "hello"
5items = [1, 2, 3]
6
7print(sys.getsizeof(number))
8print(sys.getsizeof(text))
9print(sys.getsizeof(items))

This is the right first step when you want a quick answer. It is especially useful for understanding interpreter overhead and comparing simple values such as integers, strings, tuples, and lists.

Know What Container Sizes Do and Do Not Include

A common mistake is to call getsizeof on a list or dictionary and assume that result includes every nested value. It usually does not. Containers mainly store references, so their reported size mostly reflects the container structure, not the full object graph behind it.

python
1import sys
2
3small = [1, 2, 3]
4large = ["a" * 1000, "b" * 1000, "c" * 1000]
5
6print("small list object:", sys.getsizeof(small))
7print("large list object:", sys.getsizeof(large))
8print("first large string:", sys.getsizeof(large[0]))

The two list objects can be close in size because both lists hold three references. The large strings consume much more memory, but that memory is measured on the string objects themselves, not on the list container.

Estimate Deep Size for Simple Built-In Structures

If you need an approximate total for nested built-in containers, you can walk the structure recursively. A hand-written helper is fine for local experiments, as long as you understand its limits.

python
1import sys
2
3
4def deep_size(obj):
5    size = sys.getsizeof(obj)
6
7    if isinstance(obj, dict):
8        size += sum(deep_size(key) + deep_size(value) for key, value in obj.items())
9    elif isinstance(obj, (list, tuple, set, frozenset)):
10        size += sum(deep_size(item) for item in obj)
11
12    return size
13
14
15payload = {
16    "users": [
17        {"id": 1, "name": "Ada"},
18        {"id": 2, "name": "Linus"},
19    ]
20}
21
22print(deep_size(payload))

This gives a better approximation than getsizeof alone, but it is still not perfect. Shared references may be counted more than once, and cyclic references can cause recursion problems unless you track visited object identities.

Use pympler for a Better Retained-Size View

For deeper inspection, a library such as pympler is usually more practical than a custom recursive helper.

bash
pip install pympler
python
1from pympler import asizeof
2
3data = {
4    "ids": list(range(1000)),
5    "names": ["user-" + str(i) for i in range(1000)],
6}
7
8print(asizeof.asizeof(data))

asizeof traverses object graphs more carefully and is a better fit when you are analyzing real application memory. It is not a replacement for a full profiler, but it is far more informative than checking only the top-level container size.

Interpret Results in Context

Python memory behavior depends on the interpreter implementation. CPython stores object metadata such as type information and reference counts, so even small values carry overhead. Two similar-looking objects can also reserve different amounts of capacity depending on how they were created or grown.

That means size numbers are best used comparatively, not as universal constants. If your real goal is process-level memory debugging, combine object inspection with tools such as tracemalloc, heap profilers, or container metrics. Object size is one useful signal, not the whole story.

Common Pitfalls

  • Assuming sys.getsizeof returns the full memory footprint of nested lists, dicts, or custom object graphs.
  • Comparing reported sizes across Python versions or interpreters as if they were guaranteed to match exactly.
  • Writing recursive size helpers that double-count shared objects.
  • Forgetting to guard against cyclic references in recursive traversal code.
  • Treating one object-size number as a substitute for full application memory profiling.

Summary

  • Use sys.getsizeof for the immediate size of a single object.
  • Expect container sizes to exclude most referenced contents.
  • Recursive helpers can estimate deep size for simple experiments.
  • Use pympler.asizeof when you need a more realistic retained-size estimate.
  • Read size numbers in the context of Python's interpreter overhead and your broader memory-debugging goal.

Course illustration
Course illustration

All Rights Reserved.