References and Copies

This is the single most surprising rule in both languages, and it explains bugs that otherwise look like magic.

When you assign a number or a string to a new variable, the value is copied. When you assign a list, array, dictionary, or object, the value is not copied. Both names point at the same object in memory.

EXAMPLE
loading editor…
YOUR TURN
Your turn → `b` kept its own 10. But `y` shows the appended 4, because y and x are two names for one list. Change the line that creates y so it gets its own copy (x.copy() in Python, [...x] in JavaScript), then run it and confirm y no longer shows the 4.
loading editor…

Syntax has to be exact. Every quote, bracket and parenthesis needs its partner, and in Python the spaces at the start of a line count. One slip and the program won't run; the message will say where.

✦ Two names, one object

y = x does not mean 'make me a copy of x'. It means 'let y also refer to whatever x refers to'. For a number that distinction is invisible. For a list it is everything.

When you genuinely want an independent copy, ask for one explicitly.

Making a real copy

PYTHON

original = [1, 2, 3]
copy = original.copy()      # or list(original)
copy.append(4)

print(original)   # unchanged

JAVASCRIPT

const original = [1, 2, 3];
const copy = [...original];  // or original.slice()
copy.push(4);

console.log(original); // unchanged
Compare → Python offers .copy() and list(). JavaScript uses the spread operator [...arr] or .slice(). All of them produce a genuinely separate list, so changes to one no longer touch the other.
EXAMPLE
loading editor…
YOUR TURN
Your turn → Now delete the .copy() and the spread, rerun, and watch the backup get corrupted. That is the bug this lesson prevents.
loading editor…

Syntax has to be exact. Every quote, bracket and parenthesis needs its partner, and in Python the spaces at the start of a line count. One slip and the program won't run; the message will say where.

Mark this lesson complete

Signed in, your progress follows you to every device.

Next: Sorting and Ordering →
← Back