Free preview

117 lessons

Essential Python for Data Science and ML

Free preview

Essential Python for Data Science and ML · 117 lessons

Learn Python properly - from basics to ML-ready

No surprise gaps

Actually remember it

Skip what you know

One subscription. All learning paths included.

Our content is best on a larger screen

Variables and object references

Variables hold references to objects

Explanation

In Python, variables don't store data directly - they hold references to objects that contain the data.

x = [1, 2, 3]

This means x references a list object in memory:

variable_referencing

The bottom shows the incorrect mental model - x isn't a box containing values.

Why this matters

Let's explore why we need to care about this with an example.

x = [1, 2, 3]
y = x
x.append(4)
print(y)  # Output: [1, 2, 3, 4]

Here's what happens:

  1. x = [1, 2, 3] creates a list object and x references it
  2. y = x makes y reference the same list (no copy is made)
  3. x.append(4) modifies the list
  4. Printing y shows the change - because both variables point to the same object

When we assign y = x, we're binding y to the same object - not copying it. Think of variables as "labels" attached to objects:

variable_as_labels

Warning

Be careful - modifying a mutable object through one variable affects all variables referencing it.

Info

This behaviour occurs with mutable objects like lists. With immutable objects (strings, tuples), we can't modify the object itself - we can only reassign the variable to a new object.

Practice questions

4 questions

Without writing code, what will the following code output?

x = [5, 6, 7]
y = x
x.append(8)
print(y)

Select the correct answer:

+ 3 more questions

Using id() to inspect object references and memory location

Explanation

In Python, every variable holds a reference to an object, and each object is stored at a particular location in memory.

The id() function returns an object's unique identifier (its memory address):

x = [1, 2, 3]
print(id(x))  # Output: e.g. 4402858432

If two variables reference the same object, they share the same id:

y = x
print(id(x))  # Output: 4402858432
print(id(y))  # Output: 4402858432 (same!)

This confirms x and y are labels pointing to the same object in memory.

Practice questions

4 questions

Which of the following statements about the id() function in Python is true?

Select the correct answer:

+ 3 more questions