Editor settings

General settings

Save settings

Learn to program with Python

Variable assignment with mutable objects #

Mutable objects in Python, such as dicts and lists, are passed by reference, meaning that if we assign a mutable object to multiple variables, they all point to the same memory location. Modifying the object through one variable will affect all the other variables referencing the same object.

For example:

person_a = {"name": "Coco"}
person_b = person_a # <-- Assign with existing dictionary
person_b["name"] = "Lala"
print(person_a) # {'name': 'Lala'}
print(person_b) # {'name': 'Lala'}
flowchart
    person_a --> person["{'name': 'Coco'} -> {'name': 'Lala'}"]
    person_b --> person

When we change the object in place, Python does not create a new object.

In this example, we modified the dict's name value, which affected both person_a and person_b. This is because they both point to the same object in the memory. The same happens for lists as well.

list_a = [1, 2, 3]
list_b = list_a # <-- Assign with existing list
list_a.append(4)
print(list_a) # [1, 2, 3, 4]
print(list_b) # [1, 2, 3, 4]

Exercise #

Take a look at the code below:

animal_a = {"type": "Dog"}
animal_b = animal_a
animal_a["name"] = "Fluffy"
  1. What is the value of animal_a?
  2. What is the value of animal_b?

Tests #

  • What is the value of animal_a?
  • What is the value of animal_b?
Output will be displayed here