Memory in Python, pandas and DuckDB

Part of the free LogicWiz Data Engineering course, Module 3: Python for data wrangling. The SQL and Python run in the app, on real Postgres and real Python in the browser.

It is 9:20 on Friday. You load one day of orders, a 2 GB CSV, into a list of dicts on a laptop with 16 GB of memory, and the process dies. In pandas the same file fits, but del df does not give the memory back. Then Nora runs the same sum in DuckDB with a limit of 1 GB, and it finishes. "Same data, three memory bills," she says. "Read them one at a time."

You'll learn to

  • Size Python objects, and say why a list of dicts is huge
  • Explain reference counting, cycles, and why freed memory can stay
  • Shrink a pandas frame, and tell a view from a copy
  • Run DuckDB under a memory limit and fetch results in batches

Learn

Bill one: every value is an object

Start with the crash. A 2 GB file killed a 16 GB laptop. To see why, weigh the smallest things first.

In Python every value is an object, even the number 3. Each object starts with a header: a counter and a pointer to its type, 16 bytes on a 64-bit machine, before any data. So an int costs 28 bytes, not 8, and an empty str costs 41. A list or a dict does not hold values at all. It holds pointers to other objects, 8 bytes each.

sys.getsizeof(x) gives the size of x itself, never of what it points to. Run it on a few values. One warning: this browser is a 32-bit build, so its headers and pointers are half the size of a server's. The table after the card shows both.

Sizes in this browser

import sys, struct
from decimal import Decimal

print("pointer bytes:", struct.calcsize("P"))
for value in [0, 2**30, 1.0, "", "placed", None, (), (1, 2, 3), [], {}, Decimal("12.50")]:
    print(f"{value!r:16} {sys.getsizeof(value)}")

struct.calcsize("P") is the size of a pointer: 4 bytes here, 8 on a 64-bit server. Even 0 takes 16 bytes here, and an empty dict 40.

sys.getsizeof in CPython 3.12, in bytes

ObjectThis browser (32-bit)64-bit serverWhat the bytes are
0, 1, 10011628header, length, one 30-bit digit
2302032a second digit
1.01624header and a C double
"" / "placed"21 / 2741 / 47string header, then 1 byte per ASCII character
"é"3361a non-ASCII string has a bigger header
None816header only; one shared object
() / (1, 2, 3)20 / 3240 / 64plus one pointer per item
[]2856plus a separate, over-allocated pointer array
{} / three keys40 / 10864 / 184a hash table that grows in steps
set()108216room for 8 slots up front
Decimal("12.50")52104a C struct with its own digits

Read across: the same object in this browser and on a server. Measured with Pyodide 0.26.4 (CPython 3.12.1) and CPython 3.12.14 on 64-bit macOS. Quote the 64-bit column in interviews; the browser column answers this lesson's practice.

Four ways to hold the same row

Now build a row out of those objects. There are four common layouts, and they cost very different amounts.

A list of dicts pays for a dict per row, with its own hash table, plus an object for every value. A list of tuples drops the hash table: the column names live once, outside the rows. A dict of lists, one list per column, drops the per-row container, but every value is still its own object.

A typed array is different in kind. NumPy, pandas, Arrow and DuckDB store raw values back to back: 8 bytes for an int64 or a timestamp, 1 byte for a small code, and no objects at all.

One order row is 61 bytes as CSV text. Guess what it costs as a dict.

Bytes per order row, 6 columns, 64-bit CPython 3.12

Bars compare the bytes one six-column order row takes: 61 as CSV text, 522 as a dict, 338 as a tuple, 292 in a dict of lists, and 34 in typed columns.

Measured on 10,000 orders, ids as ints and every string its own object, counting each object once (the way deep() did in Lesson 3.2). The green bar is computed: two int64, two datetime64[ns] and two one-byte category codes. At 8.6 times, the 2 GB file needs about 17 GB as dicts.

Measure it: current and peak

import csv, tracemalloc
import numpy as np

with open("data/orders.csv", newline="") as f:
    base = list(csv.DictReader(f))
src = [r for _ in range(500) for r in base]     # 40,000 rows

def measure(build):
    tracemalloc.start()
    obj = build()
    current, peak = tracemalloc.get_traced_memory()
    tracemalloc.stop()
    return f"current {current / 1e6:.2f} MB, peak {peak / 1e6:.2f} MB"

print("dicts :", measure(lambda: [{**r, "order_id": int(r["order_id"])} for r in src]))
print("tuples:", measure(lambda: [(int(r["order_id"]), r["status"]) for r in src]))
print("array :", measure(lambda: np.array([int(r["order_id"]) for r in src], dtype=np.int64)))

tracemalloc.start()
rows = [dict(r) for r in src]
top = tracemalloc.take_snapshot().statistics("lineno")[0]
tracemalloc.stop()
print("biggest line:", top.size // 1000, "KB in", top.count, "blocks")

tracemalloc reports the memory Python allocated: how much is held now, and the highest point it reached. Dicts take the most, tuples far less, the array least. But look at the array's peak: several times its current size, because the temporary list of ints lived until np.array had copied it. Peaks are what kill jobs. NumPy reports its buffers to tracemalloc, so arrays are counted too.

Remember: a Python container holds pointers to objects; a typed column holds the raw values. Convert to typed columns early, or never build the objects at all.

Who gives the memory back

The second mystery: del df did not shrink the process. To see why, you need to know how Python frees memory at all.

Every object keeps a count of the references that point at it: a name, a slot in a list, an argument. This is reference counting. When the count drops to 0, the object is freed at once, and everything it pointed to loses a reference too. That is why streaming works: the previous line's objects are gone the moment the loop moves on.

There is one gap. Two objects that point at each other keep each other's count at 1, even when nothing else can reach them. That is a reference cycle, and counting alone would never free it. Python has a second mechanism for that: the cycle collector.

A reference cycle, step by step

Two objects each start with a count of 1 from their names; pointing at each other raises both counts to 2; deleting the names leaves both at 1 and unreachable; the cycle collector then finds and frees them.

  1. Two objects, two names. a = Node() and b = Node(). Each object has one reference, from its name. Count 1 each.

  2. They point at each other. a.other = b and b.other = a. Each object now has two references: its name and the other object. Count 2 each.

  3. The names go away. del a, b. Each count drops to 1, held only by the other object. Nothing in your program can reach them, yet they are still in memory.

  4. The cycle collector runs. It looks at the pair, sets aside the references that come from inside it, finds both counts at 0, and frees them.

The left box is what your code can name. The right box is what sits in memory. Watch the counts on the right.

Counts, a cycle and the collector

import gc, sys, weakref

x = []
y = x
holder = [x, x]
print("references to x:", sys.getrefcount(x) - 1)

class Node:
    pass

gc.disable()                  # so the collector cannot run at a random moment
a, b = Node(), Node()
a.other, b.other = b, a
probe = weakref.ref(a)        # watches a without keeping it alive
del a, b
print("alive after del:", probe() is not None)
gc.collect()
print("alive after gc.collect():", probe() is not None)
gc.enable()
print("thresholds:", gc.get_threshold())

Line 1: x is held by the names x and y and by both slots of holder, so 4 references (getrefcount adds one for its own argument, which the code subtracts). Lines 2 and 3 are the picture: alive after del, gone after gc.collect(). A weakref watches an object without keeping it alive. gc.disable() is only there so the demo behaves the same on every run.

del frees nothing while another reference exists. A second name, a cache, a list of results or an exception's traceback (which keeps every frame's local variables alive) all hold objects. In IPython and Jupyter, _ and Out[n] keep the last results too. And never downcast with a bare astype: astype("int8") turns 300 into 44 without a warning. Check the range, or use pd.to_numeric(..., downcast="integer").

Freed, but not given back

When Python frees an object, the memory does not go straight back to the operating system. Small objects, up to 512 bytes, come from Python's own allocator, pymalloc. It takes memory from the system in blocks of 1 MiB called arenas, and it hands an arena back only when every single object in it is free.

So after a big del, a few survivors scattered across many arenas can keep nearly all of them. Python will reuse that space for new objects. But the operating system still counts it as yours.

That gives you two numbers to watch. tracemalloc shows what Python has allocated. RSS, the resident memory of the process, is what a container's memory limit sees.

Why memory stays after a big del

Four one-mebibyte arenas after a large delete: one is completely free and goes back to the operating system, two are almost empty but each kept whole by one live object, and one is full and in use.

Each box is one 1 MiB arena after a big del. Only the dashed green one goes back to the operating system. The two red ones are almost empty, yet they still count against your limit.

Bill two: what pandas counts

pandas avoids most of bill one. A numeric column is a typed array, so it costs exactly rows times bytes per value. Text is the exception: a text column has the type object, which means an array of pointers to ordinary Python strings.

That makes pandas' own report tricky. df.memory_usage() counts only the pointers. memory_usage(deep=True) adds the size of every string, even when a million rows point at the same one. Read the deep number as an upper limit.

Three levers shrink a frame. Category stores each distinct value once and a small code per row. Smaller numbers: pd.to_numeric(s, downcast="integer") picks the smallest integer type that fits. Real datetimes: 8 bytes each, against a 60-byte string.

Shrink a DataFrame

import pandas as pd

df = pd.concat([pd.read_csv("data/orders.csv")] * 1000, ignore_index=True)   # 80,000 rows
mb = lambda frame: round(frame.memory_usage(deep=True).sum() / 1e6, 2)
print({c: str(t) for c, t in df.dtypes.items()})
print("shallow", round(df.memory_usage().sum() / 1e6, 2), "MB | deep", mb(df), "MB")

slim = df.assign(
    order_id=pd.to_numeric(df["order_id"], downcast="integer"),
    customer_id=pd.to_numeric(df["customer_id"], downcast="integer"),
    order_ts=pd.to_datetime(df["order_ts"]),
    updated_at=pd.to_datetime(df["updated_at"]),
    status=df["status"].astype("category"),
    currency=df["currency"].astype("category"),
)
print({c: str(t) for c, t in slim.dtypes.items()})
print("deep after", mb(slim), "MB")
print(pd.Series([100, 200, 300]).astype("int8").tolist(), "<- astype wraps without a warning")

About 13 MB becomes under 2 MB. downcast checked the ranges and chose int16 and int8, the timestamps became real datetimes, and the two text columns became categories. The "before" number is a deep count, so it is too high: concat repeated the same strings. The last line shows the trap: a bare astype("int8") does not check the range, and 300 silently becomes 44.

Copies, views and copy-on-write

The pandas bill has one more line: copies. Some operations hand you a new array. Others hand you a window onto the old one.

In NumPy, a plain slice such as a[1:3] is a view: a small new header over the same data. Writing through it changes the original. Picking elements with a list or a mask, a[[0, 2]] or a[a > 0], always makes a copy. A view is free. A copy of a 1 GB column is another 1 GB.

Older pandas mixed the two: s = df["qty"] might be a view, while df[df.qty > 1]["qty"] = 0 might change nothing. Copy-on-write ends the guessing. Every object you derive behaves like a copy, but shares memory with its parent until one of them is written.

Copy-on-write: share until someone writes

A Series taken from a DataFrame shares the column buffer; when the Series is written, copy-on-write copies the column first so the DataFrame keeps its values, while without copy-on-write the write lands in the shared buffer.

Read it top to bottom. Above the line, with copy-on-write: the write makes a private copy first, and df keeps its values. Below the line, without it: the write lands in the shared data and df changes too. It saves memory as well: rename, reset_index or picking columns no longer copy anything up front.

Views, copies and copy-on-write, run for real

import numpy as np, pandas as pd

a = np.arange(6)
view, copy = a[::2], a[[0, 2]]
view[0], copy[1] = 99, -1
print(a.tolist(), np.shares_memory(a, view), np.shares_memory(a, copy))

for cow in [False, True]:
    pd.set_option("mode.copy_on_write", cow)
    df = pd.DataFrame({"qty": [1, 2, 3]})
    s = df["qty"]
    s.iloc[0] = 99
    print("copy_on_write =", cow, "-> df.qty is", df["qty"].tolist())
pd.set_option("mode.copy_on_write", False)

Line 1: writing through the view changed a[0] to 99, and writing to the copy changed nothing (np.shares_memory confirms which is which). Lines 2 and 3: the same pandas code with copy-on-write off, then on. This browser has pandas 2.2, so both can be shown. Write new code so that it passes with copy-on-write on: it is the only mode in pandas 3.0.

Bill three: DuckDB under a limit

Now Nora's run. DuckDB summed the same file with 1 GB, less than the file itself. How?

DuckDB keeps its working data, table pages, hash tables and sorted runs, in one managed pool, and memory_limit sets the size of that pool. When a GROUP BY, a join or a sort needs more than the pool holds, DuckDB does not die. It writes part of its work to a temporary folder on disk and reads it back later. That is called spilling.

One part of the bill is still yours. fetchall() builds a Python tuple for every row of the result, outside the limit. fetchmany(n) hands Python one batch at a time.

Where a DuckDB query keeps its data

Inside the Python process, DuckDB's buffer manager holds pages, hash tables and sort runs under memory_limit, while Python objects built by fetchall live outside it; spilled blocks go to the temp directory on disk.

The outer box is your Python process. The blue box is DuckDB's pool, held under memory_limit. The red box is outside the limit: the Python objects you build from the result. The dashed box is disk, where DuckDB puts what does not fit.

DuckDB under a limit, and streaming into Python

import duckdb, tracemalloc

con = duckdb.connect()
con.execute("SET memory_limit = '1GB'")
print("memory_limit:", con.sql("SELECT current_setting('memory_limit')").fetchone()[0])

con.execute("SET memory_limit = '30MB'")
try:
    con.sql("SELECT i % 1000000 AS k, count(*) FROM range(3000000) t(i) GROUP BY k").fetchall()
except duckdb.Error as e:
    print(type(e).__name__, "|", str(e)[:58])
con.execute("SET memory_limit = '500MB'")

def peak_mb(fn):
    tracemalloc.start()
    fn()
    peak = tracemalloc.get_traced_memory()[1]
    tracemalloc.stop()
    return round(peak / 1e6, 1)

def all_at_once():
    return len(con.execute("SELECT i, i * 2 AS x FROM range(300000) t(i)").fetchall())

def in_batches():
    cur, n = con.execute("SELECT i, i * 2 AS x FROM range(300000) t(i)"), 0
    while batch := cur.fetchmany(10_000):
        n += len(batch)
    return n

print("Python peak, fetchall:", peak_mb(all_at_once), "MB | fetchmany:", peak_mb(in_batches), "MB")

Line 1: 1GB is read as 10^9 bytes and shown as 953.6 MiB. Line 2: a million groups do not fit in 30 MB, and in this browser DuckDB cannot spill, so it stops with Out of Memory Error. With a disk it would spill and finish. Line 3 is Python's side only: about 19 MB to hold every row with fetchall, about 1 MB with fetchmany.

Numbers to remember

WhatNumberGood to know
An object header on 64-bit CPython16 bytesa count and a type pointer; a container holds 8-byte pointers
sys.getsizeof of a list of a million long stringsabout 8 MBit counts the pointers, never the strings
Immortal objectssince Python 3.12 (PEP 683)None, True, small ints and other built-in singletons: their count never changes
gc.getthreshold() in 3.12(700, 10, 10)the collector tracks only containers, in three generations; a young pass starts when allocations minus deallocations exceed 700
The collector in Python 3.14incremental in 3.14.0 to 3.14.43.14.5 went back to the 3.13 generational one after reports of memory pressure
pymallocobjects up to 512 bytes, in 1 MiB arenas256 KiB arenas on 32-bit builds
A category columnint8 codes while there are fewer than 127 categorieseach distinct value is stored once
datetime64[ns]8 bytesagainst a 60-byte string on 64-bit CPython
Copy-on-write in pandasopt-in in 2.x, the only mode in 3.0 (January 2026)pd.options.mode.copyonwrite = True, or "warn" in 2.2; 3.0 removes SettingWithCopyWarning, and chained assignment never works and warns with ChainedAssignmentError
DuckDB memorylimit80% of physical RAM by default'1GB' is read as 10^9 bytes and shown as 953.6 MiB
DuckDB maxtempdirectorysize90% of free disk by defaultspills go to tempdirectory: <database.tmp, or .tmp in memory mode
fetchdfchunk()2,048 rows by defaultfetchrecordbatch() streams Arrow batches (needs pyarrow); newer releases call it toarrowreader()

DuckDB's documented limits: several blocking operators in one query can still run out of memory, string_agg cannot be offloaded, and huge CSV or Parquet copies want SET preserve_insertion_order = false. Other engines follow the same ideas. Spark's Tungsten stores rows as binary UnsafeRows, not Java objects (Module 12), and pandas UDFs move Arrow batches, not pickled rows. Python services that hold millions of records use __slots__ classes (56 bytes for three fields on 64-bit 3.12, against 184 for a three-key dict before the values) or NumPy arrays, and size workers by their peak, not their average. pandas 3.0 also adds a dedicated str dtype, backed by pyarrow when it is installed.

What changed at SwiftKart

By Friday evening the three bills are explained, and the nightly job is rewritten around them.

It no longer builds a dict per row. It reads the day's orders straight into typed columns: ids downcast, timestamps as real datetimes, status and currency as categories. The 2 GB file now takes less memory than it takes on disk. The heavy sum runs in DuckDB under a 1 GB limit, and Python fetches the result in batches. Workers are sized by their peak, and nobody is surprised when RSS stays high after a del.

That closes Module 3: you can read, flatten, deduplicate, stream, fetch, validate and measure data in plain Python. Module 4 asks where all this data should live. Its first lesson, "Rows and columns", starts from the typed columns you met today.

In one line

Every Python value is an object with its own overhead, so keep data in typed columns, watch the peak, expect freed memory to stay with the process, and let DuckDB work under a memory_limit while Python fetches in batches.

Interview corner

Why does a list of dicts take so much more memory than the CSV it came from?

Every value becomes a heap object with a 16-byte header on 64-bit CPython: an int is 28 bytes, a string 41 bytes plus its characters, and each row adds a dict with its own hash table, 184 bytes for three keys before any values. Measured on SwiftKart's orders, a six-column row is about 61 bytes of CSV text and 522 bytes as a dict, 8.6 times. Tuples drop the per-row hash table, and typed columns (NumPy, pandas, Arrow, DuckDB) store raw values, 34 bytes for the same row. So I convert to typed columns early, or never build the dicts at all.

You `del` a large DataFrame and the process memory does not drop. Is that a leak?

Not necessarily. First I check whether anything still references it: another name, a cache, a list of results, an exception traceback, or the notebook's _ and Out. If nothing does, Python freed it, but the allocator may keep the memory: pymalloc returns a 1 MiB arena only when it is completely empty, and the C allocator also keeps freed pages, so RSS stays near the high-water mark while tracemalloc shows current usage dropping. The fix is a lower peak (smaller chunks, fewer temporaries, typed columns) or recycling long-running worker processes.

What does copy-on-write change in pandas 3.0, and why does it matter for memory?

Every indexing result and every method result behaves as a copy, but shares memory with its parent until one side is written; only then are the written columns copied. That removes the view-or-copy ambiguity: SettingWithCopyWarning is gone, and chained assignment such as df[mask]["qty"] = 0 never works and raises ChainedAssignmentError, so code must use df.loc[mask, "qty"] = 0. For memory, chains of rename, reset_index and column selections no longer make defensive copies, so peaks drop; the cost moves to the first write. In pandas 2.x it is opt-in with pd.options.mode.copy_on_write = True.

How does DuckDB run a GROUP BY bigger than memory, and what can still fail?

Its buffer manager keeps pages, hash tables and sort runs under memory_limit, 80% of RAM by default, and when an aggregate, join, sort or window grows past it, it writes blocks to temp_directory and reads them back, up to max_temp_directory_size. It can still fail with Out of Memory Error when several blocking operators run in one query, for aggregates such as string_agg that cannot be offloaded, or when the temp directory is missing or full. Two easy wins: SET preserve_insertion_order = false for big imports and exports, and fetching results in batches, because the Python objects fetchall() builds are not covered by memory_limit.