Day 2
Day 2
• Introduction
• Recap
• Mutable vs Immutable Types
• Namespaces in Python
• Garbage Collection & gc Module
• Visual Walkthrough and Examples
• Hands-on Coding Activity
• Q&A and Wrap-up
Learning Objectives
Technical Definition
• Mutability refers to whether an object's state can be modified after
creation. This property directly impacts memory allocation, performance,
and program behavior.
Key Technical Points:
• Memory Allocation Behavior: Immutable objects create new memory
locations when modified; mutable objects modify existing memory locations
• Reference Semantics: Mutable objects can have multiple references
pointing to the same memory location, leading to shared state changes
Mutable vs Immutable Types
• Immutable Types:
Data types whose value cannot be changed after creation. Examples:
int, float, str, tuple.
• Mutable Types:
Data types that allow in-place modification. Examples: list, dict, set.
• Key Point:
Variable assignment points to memory references. Mutable objects can
be changed without altering the reference.
Mutable vs Immutable Types
# Immutable
x=5
print(id(x))
x = 10
print(id(x)) # id changes
# Mutable
lst = [1, 2, 3]
print(id(lst))
lst.append(4)
print(id(lst)) # id remains same
Namespaces in Python
Technical Definition
• A namespace is a mapping from names to objects, implemented as a dictionary.
Python maintains multiple namespaces simultaneously to resolve variable names
according to the LEGB rule.
Key Technical Points:
• Namespace Hierarchy: Python maintains separate namespaces for built-in, global,
enclosing, and local scopes
• Name Resolution: The interpreter searches namespaces in LEGB order (Local →
Enclosing → Global → Built-in)
Types of Namespaces: x = "global"
• Built-in Namespace: Contains built-in functions
and exceptions (e.g., len, ValueError).
• Global Namespace: Contains names defined at def outer():
the top-level of a script or module. x = "enclosing"
• Local Namespace: Created inside functions and
def inner():
holds local variable names.
• Enclosing Namespace: Exists in nested x = "local"
functions, containing names from outer functions.
print("Inner:",
x)
inner()
print("Outer:", x)
outer()
print("Global:", x)
Garbage Collection & gc Module
Technical Definition
• Garbage Collection is Python's automatic memory management system that
deallocates objects no longer referenced by the program. It uses reference
counting combined with cycle detection.
Key Technical Points:
• Reference Counting: Python tracks the number of references to each
object; when count reaches zero, memory is immediately freed
• Cycle Detection: A separate algorithm detects and breaks circular
references that reference counting cannot handle
gc Module
• Helps in debugging memory leaks and checking for reference cycles.
Q&A
THANK YOU