Variable assignment with immutable objects #
When a variable is assigned a value in Python, the variable does not store the value itself. Instead, Python creates a reference pointing to the value in the memory.
When we create variables x and y and give them the value 10, we create a reference that points to the value 10 in the memory. We could check this by using the function id() to check their positions in the memory, and we will see that they are the same.
x = 10
y = x
print(id(x)) # 140314708984336
print(id(y)) # 140314708984336
flowchart LR x --> 10 y --> 10
In the case of immutable objects, such as strings, ints, and floats, when we reassign a new value to the variable x, Python creates a new value in the memory and updates the reference without affecting the value of y.
x = 10
print(id(x)) # 140314708984336
y = x
print(id(y)) # 140314708984336
x = 15
print(id(y)) # 140634520519344
print(x) # 15
print(y) # 10
flowchart x -.-> 10 x --> 15 y --> 10
Exercise #
Take a look at the code below:
x = "Hello World"
y = x
x = "Python is awesome!"
- What is the value of
x? - What is the value of
y?
Create a variable x and y in the editor and assign their values with the answers, then run the program.
Tests #
- What is the value of
x? - What is the value of
y?
Getting Started with Python
Data Types
Python Functions
Statements in Python
Basic Debugging in Python
Basic Algorithm
Object-Oriented Programming
Error Handling
Intermediate Algorithm
Python Modules