Here's the script a lot of people write in their first fortnight with functions (a function is a named, reusable block of code). Save it as game.py in an empty folder, open the terminal (the text window where you type commands) there, and run 'python3 game.py' (on Windows, 'python game.py'). A dictionary, written with curly braces, is a collection of labelled values:
def add_bonus(player):
player['score'] += 10
return player
me = {'name': 'Sam', 'score': 50}
result = add_bonus(me)
print(me)
You wanted the bonus in 'result'. You expected 'me' to stay at 50. The 'print' line shows 'me', and it prints this:
{'name': 'Sam', 'score': 60}
Nothing is random here. Python did exactly what the code said. The trouble is that the picture most of us carry in our heads is wrong. The word for what happened is mutate: changing a thing in place instead of making a new one. (An object is just a thing Python holds in memory: a number, a piece of text, a list or a dictionary.) By the end you'll know why a function can change your data behind your back, how to check it with 'id()' and 'is', and the habit that prevents it.
What you need
Python 3 (I used 3.13.18), a terminal, and an empty folder to save the snippets in.
The concept: names point at one object, and id() shows it
The picture is that 'me' is a box with the dictionary inside, and calling the function hands over a photocopy. It doesn't. The dictionary is one object. 'me' is a name stuck to it, and the function's 'player' is a second name stuck to the same object.
You can check that rather than take my word for it. Add this line at the bottom of the script above and run it again:
print(id(me) == id(result), me is result)
True True
'id()' gives you an object's identity number, like a serial number for the thing in memory, and 'is' asks whether two names point at the same object. The first half of that line compares the two ids with '==', which asks whether two values are equal. Both say yes. There was never a copy, and 'player['score'] += 10' reached through the second name and edited the one dictionary. I ran every core snippet in this piece on Python 3.13.18, and the sharing works the same on any Python 3 you're likely to have.
Hold on to that pair of tools. You'll use them for the rest of this article.
Show the code
<style>
.row { display: flex; flex-wrap: wrap; gap: 8px; margin: 8px 0; }
button { min-height: 40px; padding: 0 14px; font: inherit; border: 1px solid #888; border-radius: 8px; background: #f2f2f2; cursor: pointer; }
button[aria-pressed=true] { background: #dbeafe; border-color: #2563eb; }
pre { margin: 0 0 10px; white-space: pre-wrap; word-break: break-word; font-size: 15px; background: #f6f6f6; padding: 8px; border-radius: 6px; }
#code span { display: block; padding: 0 4px; border-radius: 4px; }
#code span.now { background: #fde68a; }
h3 { font-size: 16px; margin: 10px 0 6px; }
#mem { display: grid; gap: 8px; }
.obj { border: 2px solid #2563eb; border-radius: 8px; padding: 8px; font-family: monospace; font-size: 15px; word-break: break-word; }
.obj.list { border-color: #d97706; }
.tag { display: inline-block; background: #1d1d1f; color: #fff; border-radius: 12px; padding: 1px 10px; margin: 0 6px 6px 0; font-size: 15px; }
#out { background: #1d1d1f; color: #f2f2f2; min-height: 2.5em; }
</style>
<p>Pick a script, then press Step to run it one line at a time. Watch whether <code>me</code> changes.</p>
<div class="row">
<button id="sA" aria-pressed="true">Before: add_bonus(me)</button>
<button id="sB" aria-pressed="false">Before: add_item with .copy()</button>
<button id="sC" aria-pressed="false">After: add_item returns a new dict</button>
</div>
<pre id="code"></pre>
<div class="row"><button id="step">Step</button><button id="reset">Start over</button></div>
<h3>Objects in memory, with the names stuck to them</h3>
<div id="mem"></div>
<h3>Printed</h3>
<pre id="out"></pre>
<script>
const D = (tags, body, cls) => ({ tags, body, cls: cls || '' });
const SCRIPTS = {
A: {
code: ["def add_bonus(player):", " player['score'] += 10", " return player", "", "me = {'name': 'Sam', 'score': 50}", "result = add_bonus(me)", "print(me)", "print(id(me) == id(result), me is result)"],
steps: [
{ line: 4, mem: [D(['me'], "{'name': 'Sam', 'score': 50}")] },
{ line: 0, mem: [D(['me', 'player'], "{'name': 'Sam', 'score': 50}")] },
{ line: 1, mem: [D(['me', 'player'], "{'name': 'Sam', 'score': 60}")] },
{ line: 5, mem: [D(['me', 'result'], "{'name': 'Sam', 'score': 60}")] },
{ line: 6, mem: [D(['me', 'result'], "{'name': 'Sam', 'score': 60}")], out: "{'name': 'Sam', 'score': 60}" },
{ line: 7, mem: [D(['me', 'result'], "{'name': 'Sam', 'score': 60}")], out: 'True True' },
],
},
B: {
code: ["me = {'name': 'Sam', 'score': 50, 'items': ['sword']}", "", "def add_item(player):", " p = player.copy()", " p['items'].append('shield')", " p['score'] += 10", " return p", "", "new = add_item(me)", "print(me)"],
steps: [
{ line: 0, mem: [D(['me'], "{'name': 'Sam', 'score': 50, 'items': ↓}"), D(["me['items']"], "['sword']", 'list')] },
{ line: 2, mem: [D(['me', 'player'], "{'name': 'Sam', 'score': 50, 'items': ↓}"), D(["me['items']"], "['sword']", 'list')] },
{ line: 3, mem: [D(['me', 'player'], "{'name': 'Sam', 'score': 50, 'items': ↓}"), D(['p'], "{'name': 'Sam', 'score': 50, 'items': ↓}"), D(["me['items']", "p['items']"], "['sword']", 'list')] },
{ line: 4, mem: [D(['me', 'player'], "{'name': 'Sam', 'score': 50, 'items': ↓}"), D(['p'], "{'name': 'Sam', 'score': 50, 'items': ↓}"), D(["me['items']", "p['items']"], "['sword', 'shield']", 'list')] },
{ line: 5, mem: [D(['me', 'player'], "{'name': 'Sam', 'score': 50, 'items': ↓}"), D(['p'], "{'name': 'Sam', 'score': 60, 'items': ↓}"), D(["me['items']", "p['items']"], "['sword', 'shield']", 'list')] },
{ line: 8, mem: [D(['me'], "{'name': 'Sam', 'score': 50, 'items': ↓}"), D(['new'], "{'name': 'Sam', 'score': 60, 'items': ↓}"), D(["me['items']", "new['items']"], "['sword', 'shield']", 'list')] },
{ line: 9, mem: [D(['me'], "{'name': 'Sam', 'score': 50, 'items': ↓}"), D(['new'], "{'name': 'Sam', 'score': 60, 'items': ↓}"), D(["me['items']", "new['items']"], "['sword', 'shield']", 'list')], out: "{'name': 'Sam', 'score': 50, 'items': ['sword', 'shield']}" },
],
},
C: {
code: ["def add_item(player):", " return {", " **player,", " 'score': player['score'] + 10,", " 'items': [*player['items'], 'shield'],", " }", "", "me = {'name': 'Sam', 'score': 50, 'items': ['sword']}", "before = (id(me), id(me['items']))", "n = add_item(me)", "print(me)", "print(n)", "print(before == (id(me), id(me['items'])), n is me, n['items'] is me['items'])"],
steps: [
{ line: 7, mem: [D(['me'], "{'name': 'Sam', 'score': 50, 'items': ↓}"), D(["me['items']"], "['sword']", 'list')] },
{ line: 8, mem: [D(['me'], "{'name': 'Sam', 'score': 50, 'items': ↓}"), D(["me['items']"], "['sword']", 'list')] },
{ line: 0, mem: [D(['me', 'player'], "{'name': 'Sam', 'score': 50, 'items': ↓}"), D(["me['items']", "player['items']"], "['sword']", 'list')] },
{ line: 1, mem: [D(['me', 'player'], "{'name': 'Sam', 'score': 50, 'items': ↓}"), D(["me['items']", "player['items']"], "['sword']", 'list'), D(['(new dict)'], "{'name': 'Sam', 'score': 60, 'items': ↓}"), D(['(new list)'], "['sword', 'shield']", 'list')] },
{ line: 9, mem: [D(['me'], "{'name': 'Sam', 'score': 50, 'items': ↓}"), D(["me['items']"], "['sword']", 'list'), D(['n'], "{'name': 'Sam', 'score': 60, 'items': ↓}"), D(["n['items']"], "['sword', 'shield']", 'list')] },
{ line: 10, mem: [D(['me'], "{'name': 'Sam', 'score': 50, 'items': ↓}"), D(["me['items']"], "['sword']", 'list'), D(['n'], "{'name': 'Sam', 'score': 60, 'items': ↓}"), D(["n['items']"], "['sword', 'shield']", 'list')], out: "{'name': 'Sam', 'score': 50, 'items': ['sword']}" },
{ line: 11, mem: [D(['me'], "{'name': 'Sam', 'score': 50, 'items': ↓}"), D(["me['items']"], "['sword']", 'list'), D(['n'], "{'name': 'Sam', 'score': 60, 'items': ↓}"), D(["n['items']"], "['sword', 'shield']", 'list')], out: "{'name': 'Sam', 'score': 60, 'items': ['sword', 'shield']}" },
{ line: 12, mem: [D(['me'], "{'name': 'Sam', 'score': 50, 'items': ↓}"), D(["me['items']"], "['sword']", 'list'), D(['n'], "{'name': 'Sam', 'score': 60, 'items': ↓}"), D(["n['items']"], "['sword', 'shield']", 'list')], out: 'True False False' },
],
},
};
let which = 'A', i = -1, printed = [];
const $ = (id) => document.getElementById(id);
function esc(s) { return s.replace(/&/g, '&').replace(/</g, '<'); }
function render() {
const s = SCRIPTS[which], st = s.steps[i];
$('code').innerHTML = s.code.map((l, n) => '<span class="' + (st && st.line === n ? 'now' : '') + '">' + (esc(l) || ' ') + '</span>').join('');
$('mem').innerHTML = st ? st.mem.map((o) => '<div class="obj ' + o.cls + '">' + o.tags.map((t) => '<span class="tag">' + esc(t) + '</span>').join('') + '<div>' + esc(o.body) + '</div></div>').join('') : '<p>(empty: press Step)</p>';
$('out').textContent = printed.join('\n');
$('step').disabled = i >= s.steps.length - 1;
}
$('step').onclick = () => {
const s = SCRIPTS[which];
if (i >= s.steps.length - 1) return;
i++;
if (s.steps[i].out) printed.push(s.steps[i].out);
render();
};
function start(w) {
which = w; i = -1; printed = [];
$('sA').setAttribute('aria-pressed', w === 'A'); $('sB').setAttribute('aria-pressed', w === 'B'); $('sC').setAttribute('aria-pressed', w === 'C');
render();
}
$('reset').onclick = () => start(which);
$('sA').onclick = () => start('A');
$('sB').onclick = () => start('B');
$('sC').onclick = () => start('C');
start('A');
</script>Walkthrough: the fix you already tried
So you reach for a copy. Both of these make a new dictionary (the dot in 'me.copy()' means "ask this object to do its copy method"):
safe = me.copy() safe = dict(me)
For a flat dictionary like 'me' above, that works. Edit 'safe' and 'me' stays put. Then your game grows an inventory, a list (an ordered collection, written with square brackets) stored inside the dictionary. In the function below, '.append' adds an item to the end of a list:
me = {'name': 'Sam', 'score': 50, 'items': ['sword']}
def add_item(player):
p = player.copy()
p['items'].append('shield')
p['score'] += 10
return p
new = add_item(me)
print(me)
{'name': 'Sam', 'score': 50, 'items': ['sword', 'shield']}
Look closely. The score is still 50, so the copy did its job. But the shield is in your original inventory. You copied the dictionary and the bug survived anyway.
Ask the question the same way as before:
c = me.copy() print(c is me, c['items'] is me['items'])
False True
Where it goes wrong: a copy is only one level deep
That's the whole mechanism. A dictionary doesn't contain its values. It holds references to them: labels pointing at objects that live elsewhere in memory. '.copy()' builds a new dictionary and copies the labels. The numbers and strings are fine, because you can't edit a number in place. The list isn't fine, because both dictionaries now hold a label to the same list.
The copy is one level deep. Whatever sits inside a value is shared. And 'dict(d)' and '{**d}' do the same thing: I checked, and both hand you the very same inner list.
deepcopy, and what it costs
Python's standard library (the toolbox that comes with Python) has a module, a file of ready-made code you pull in with 'import', that follows every label all the way down:
import copy d = copy.deepcopy(me) print(d['items'] is me['items'], d == me)
False True
Different list, same contents. ('d == me' asks whether the two are equal in value, not whether they are the same object.) It's one line, it works, and I'd use it in a pinch. But it isn't free. On a small dictionary with a ten-item list, I timed 100,000 calls on Python 3.13.18: roughly 0.005 seconds for '.copy()' and roughly 0.36 seconds for 'deepcopy()'. That's dozens of times slower, and the exact multiple depends on your machine and Python version, so time it yourself rather than trusting my number. It also grows with your data: with 100 items in the list the gap was in the hundreds of times, and with 1,000 items in the thousands. And it hides the real question, which is why a function that's meant to give you a score needed to touch your inventory in the first place.
The habit that fixes it
Here is what I'd rather you take away. Stop asking "how do I copy defensively?" and ask "why is my function editing something it was handed?"
Write the function so that it builds a new dictionary from what it receives and returns that, meaning hands it back to the caller. It never assigns into its input and never calls '.append' on anything inside it:
def add_item(player):
return {
**player,
'score': player['score'] + 10,
'items': [*player['items'], 'shield'],
}
Read what each line does. '**player' (the two stars spread a dictionary's entries out in place) lays out the old entries. 'score' is then replaced with a new number. 'items' is replaced with a brand-new list built from the old one plus the shield ('[*player['items'], 'shield']' uses one star to spread a list's items into a new list). Only the things that change get rebuilt, and everything else is shared on purpose, which is safe as long as nobody edits it.
Now prove it, using the same check as before. Record the identities first (a tuple is just a fixed pair or group of values in parentheses), call the function, then compare:
me = {'name': 'Sam', 'score': 50, 'items': ['sword']} before = (id(me), id(me['items'])) n = add_item(me) print(me) print(n) print(before == (id(me), id(me['items'])), n is me, n['items'] is me['items'])
{'name': 'Sam', 'score': 50, 'items': ['sword']} {'name': 'Sam', 'score': 60, 'items': ['sword', 'shield']} True False False
The original is untouched and still holds the same list object. The result is a different dictionary with a different list. No copy module, no cost worth measuring, and a reader of your code can see that nothing inside 'add_item' changes its input.
What about a big dictionary you really do need to change in place? Then change it in place, and give the function a name that says so, something like 'apply_bonus_to'. The mistake isn't mutation. The mistake is mutation nobody expected. A function called 'add_bonus' that returns a value is promising not to touch your data.
Optional footnote: freezing the container is not freezing the contents
You can skip this part. It needs Python 3.15 or later. Python 3.15 adds a built-in 'frozendict' (see the What's New in Python 3.15 page at docs.python.org/3.15/whatsnew/3.15.html), a dictionary that refuses to change. I ran this on a 3.15 beta build, and 'sys.version' printed '3.15.0b4 (main, Jul 18 2026, 17:04:20) [Clang 22.1.3 ]', so check the output on the release you have installed. On 3.13 the name doesn't exist and the very first line stops with a NameError (Python's way of saying "I don't know that name"), so you need 3.15 to follow along. The try/except below runs the risky line and, if it fails, catches the TypeError (the error Python raises when an operation doesn't fit the object) that frozendict raises when you try to change it:
d = frozendict({'items': ['sword']}) try: d['score'] = 1 except TypeError as e: print('TypeError:', e)
TypeError: 'frozendict' object does not support item assignment
That would have caught the first bug in this article loudly instead of quietly. But it only guards the dictionary itself:
d['items'].append('shield') print(d) print(isinstance(d, dict))
frozendict({'items': ['sword', 'shield']}) False
The list inside took the append anyway. Freezing the container does not freeze what's inside it, which is the same one-level-deep rule wearing a different coat. And 'isinstance(d, dict)' (which asks whether an object is a dictionary) printing False means it's a separate type, not a locked dict. It won't replace the habit above.
Recap
- A name is a label on an object; passing a dictionary to a function hands over the same object, not a photocopy.
- 'id()' and 'is' tell you whether two names point at one object.
- '.copy()', 'dict(d)' and '{**d}' copy one level only, so inner lists stay shared.
- 'deepcopy' fixes that but is slower; the better habit is a function that returns a new dictionary and never edits its input.
Try it on your own code. Pick one function you wrote this week that takes a dictionary or a list. Before the call, save 'before = id(your_data)' and, for a nested value, 'id(your_data['something'])'. Call the function. Print both ids again, then print the data itself. If the ids match but the contents changed, your function edited its input. Rewrite it to return a new dictionary, run the same check, and watch the contents stop moving.