Python: Variable Assigment
Python Variable Assigment
1 Overview
📘 Variable Assigment
In Python, variable assignment is the process where you use the assignment operator = to give a name (the variable) to a value (the object). Variables in Python do not have a fixed type; a variable can point to any kind of object, and you can reassign it to a different type later. This flexible behavior is called dynamic typing.
2 Variable Assigment
In Python, everything is an object (we will better define this in future lessons). Each object has a type, a value, and a unique identity (its address in memory). When using the assignment operator =
, we are attaching a name to an object.
For example:
Let’s see a more complex example:
- An
int
with value 3 is stored in memory and assigned to the namea
. - Name
b
is assigned to the same object in memory asa
. - The same occurs with
c
; all three share the same memory address.
If we reassign the variable a
with a new value:
- A new object with that value is allocated in memory
a
now points to itb
andc
remain unaltered, pointing to the original memory address
If two or more names point to the same memory location and we modify the contents, the value is altered in all the variables:
2.1 The is
Keyword
Used for identity comparison.
==
is used to compare the values of two objects to check if they are equal.is
checks if two variables refer to the same object in memory.
Example:
2.2 Memory Optimization of Immutables
Python may optimize memory use by reusing the same memory location for multiple variables:
- Occurs for some small
int
s, short strings, or short tuples.
Example:
But for longer strings:
Typical reuse occurs with int
s between -5 and 256:
3 Garbage Collection (GC)
- The garbage collector is a built-in system in Python that frees memory from objects no longer in use.
- Works alongside reference counting.
3.1 Reference Counting
- The main memory management technique in Python.
- Objects have a count of references to them.
- When the count drops to zero, memory is deallocated.
Example: