Pass by Object Reference in Python
Is Python pass-by-value or pass-by-reference?
β‘οΈ Actually, Python uses Pass by Object Reference.
That means:
The function receives a reference to the same object.
π Example: Mutable Object
π The original list changed
Because the function received a reference
to the SAME object in memory.
π Example: Immutable Object
π Integer did not change
Because integers are immutable
Reassignment creates a new object.
π― Core Idea
β’ Functions receive object references
β’ Mutable objects can be modified
β’ Immutable objects create new objects
β’ Python is NOT pure pass-by-value
β’ Python is NOT pure pass-by-reference
β It is Pass by Object Reference.
Is Python pass-by-value or pass-by-reference?
β‘οΈ Actually, Python uses Pass by Object Reference.
That means:
The function receives a reference to the same object.
π Example: Mutable Object
def modify(lst):
lst.append(4)
nums = [1, 2, 3]
modify(nums)
print(nums)
Output:
[1, 2, 3, 4]
π The original list changed
Because the function received a reference
to the SAME object in memory.
π Example: Immutable Object
def modify(x):
x = x + 1
print("Inside:", x)
num = 10
modify(num)
print("Outside:", num)
Output:
Inside: 11
Outside: 10
π Integer did not change
Because integers are immutable
Reassignment creates a new object.
π― Core Idea
β’ Functions receive object references
β’ Mutable objects can be modified
β’ Immutable objects create new objects
β’ Python is NOT pure pass-by-value
β’ Python is NOT pure pass-by-reference
β It is Pass by Object Reference.
β€4
π§ Garbage Collection & Reference Counting in Python
Python automatically manages memory.
Objects are deleted when they are no longer used.
π Reference Counting
Every object tracks how many variables point to it.
When the count becomes 0, it is removed.
π Circular Reference Problem
Two objects pointing to each other
will never reach reference count 0.
π Garbage Collector (GC)
Pythonβs GC:
β’ Detects unreachable cycles
β’ Breaks circular references
β’ Frees memory safely
π― Core Idea
Reference Counting β Main mechanism
GC β Handles circular references
Python automatically manages memory.
Objects are deleted when they are no longer used.
π Reference Counting
Every object tracks how many variables point to it.
When the count becomes 0, it is removed.
a = [1, 2, 3]
b = a
del a
del b
Reference count:
a β 1
a, b β 2
after del β 0
Object deleted
π Circular Reference Problem
Two objects pointing to each other
will never reach reference count 0.
class Node:
def __init__(self):
self.ref = None
a = Node()
b = Node()
a.ref = b
b.ref = a
del a
del b
Both objects still reference each other
Reference count β 0
π Garbage Collector (GC)
Pythonβs GC:
β’ Detects unreachable cycles
β’ Breaks circular references
β’ Frees memory safely
π― Core Idea
Reference Counting β Main mechanism
GC β Handles circular references
β€4
π₯ is vs == in Python
Many developers confuse these two operators.
But they check completely different things.
π == (Equality Operator)
```text
Output:
True
a = [1, 2, 3]
b = [1, 2, 3]
print(a is b)
Output:
False
x = [1, 2, 3]
y = x
print(x is y)
Output:
True
π Both reference the SAME object
π― Quick Difference
β’
β’
β’ Use
β’ Use
Many developers confuse these two operators.
But they check completely different things.
π == (Equality Operator)
== checks whether values are equal.a = [1, 2, 3]
b = [1, 2, 3]
print(a == b)
```text
Output:
True
python
π Values are the same
π Even though they are different objects
π is (Identity Operator)
is checks whether two variables point to the same object in memory.
a = [1, 2, 3]
b = [1, 2, 3]
print(a is b)
text
Output:
False
python
π They are stored at different memory locations
π So identity is different
π When is returns True
x = [1, 2, 3]
y = x
print(x is y)
text
Output:
True
`π Both reference the SAME object
π― Quick Difference
β’
== β Compares values β’
is β Compares memory identity β’ Use
== for value comparison β’ Use
is mainly for None checksβ€5
π Shallow Copy vs Deep Copy in Python
When copying objects in Python, behavior changes for nested data structures.
π Shallow Copy
A shallow copy creates a new outer object
but inner objects remain shared references π
π Nested objects are shared.
π Deep Copy
A deep copy creates a completely independent copy
including all nested objects π§
π No shared references.
π― Quick Difference
β’ Shallow β Copies outer layer only
β’ Deep β Copies entire structure
β’ Use deep copy for nested data
When copying objects in Python, behavior changes for nested data structures.
π Shallow Copy
A shallow copy creates a new outer object
but inner objects remain shared references π
import copy
original = [[1, 2], [3, 4]]
shallow = copy.copy(original)
shallow[0].append(99)
print(original)
print(shallow)
Output:
[[1, 2, 99], [3, 4]]
[[1, 2, 99], [3, 4]]
π Nested objects are shared.
π Deep Copy
A deep copy creates a completely independent copy
including all nested objects π§
import copy
original = [[1, 2], [3, 4]]
deep = copy.deepcopy(original)
deep[0].append(99)
print(original)
print(deep)
Output:
[[1, 2], [3, 4]]
[[1, 2, 99], [3, 4]]
π No shared references.
π― Quick Difference
β’ Shallow β Copies outer layer only
β’ Deep β Copies entire structure
β’ Use deep copy for nested data
β€4
Forwarded from Programming Quiz Channel
In Python, deepcopy is needed for:
Anonymous Quiz
15%
numbers
13%
strings
16%
tuples
57%
nested objects
π§ LEGB Rule in Python (Scope Resolution)
When Python looks for a variable,
it follows a fixed order called LEGB.
L β Local
E β Enclosing
G β Global
B β Built-in
Python searches in this order.
1οΈβ£ Local Scope (L) π
Variables defined inside a function.
Output:
β€ Python finds
2οΈβ£ Enclosing Scope (E) π
Variables in outer function (nested functions).
Output:
β€ Python finds
3οΈβ£ Global Scope (G) π
Variables defined outside all functions.
Output:
β€ Python uses global
4οΈβ£ Built-in Scope (B) βοΈ
Predefined names like
Output:
π‘ Search Order
Local β Enclosing β Global β Built-in
Python stops searching once it finds the name.
When Python looks for a variable,
it follows a fixed order called LEGB.
L β Local
E β Enclosing
G β Global
B β Built-in
Python searches in this order.
1οΈβ£ Local Scope (L) π
Variables defined inside a function.
x = 10
def func():
x = 5
print(x)
func()
Output:
5β€ Python finds
x inside the function first.2οΈβ£ Enclosing Scope (E) π
Variables in outer function (nested functions).
def outer():
x = 20
def inner():
print(x)
inner()
outer()
Output:
20β€ Python finds
x in the enclosing function.3οΈβ£ Global Scope (G) π
Variables defined outside all functions.
x = 30
def func():
print(x)
func()
Output:
30β€ Python uses global
x.4οΈβ£ Built-in Scope (B) βοΈ
Predefined names like
len, print, etc.print(len([1, 2, 3]))
Output:
3π‘ Search Order
Local β Enclosing β Global β Built-in
Python stops searching once it finds the name.
β€3
π List vs Tuple in Python
Both store collections of data.
But they differ in mutability and internal behavior.
1οΈβ£ List (Mutable) π¦
Can be modified after creation.
Output:
β€ How: Stored as a dynamic array
β€ Wins: Flexible, easy to modify
β€ Risk: Slightly higher memory usage
2οΈβ£ Tuple (Immutable) π
Cannot be modified after creation.
Output:
β€ How: Fixed-size structure
β€ Wins: Faster iteration, lower memory usage
β€ Risk: No modification allowed
π‘ Key Difference
β’ List β Mutable & flexible
β’ Tuple β Immutable & lightweight
Use List when data changes.
Use Tuple when data should stay constant.
Both store collections of data.
But they differ in mutability and internal behavior.
1οΈβ£ List (Mutable) π¦
Can be modified after creation.
nums = [1, 2, 3]
nums.append(4)
print(nums)
Output:
[1, 2, 3, 4]β€ How: Stored as a dynamic array
β€ Wins: Flexible, easy to modify
β€ Risk: Slightly higher memory usage
2οΈβ£ Tuple (Immutable) π
Cannot be modified after creation.
nums = (1, 2, 3)
nums.append(4)
Output:
AttributeError: 'tuple' object has no attribute 'append'β€ How: Fixed-size structure
β€ Wins: Faster iteration, lower memory usage
β€ Risk: No modification allowed
π‘ Key Difference
β’ List β Mutable & flexible
β’ Tuple β Immutable & lightweight
Use List when data changes.
Use Tuple when data should stay constant.
β€5
π Letβs Fix How Youβre Learning Python
If you feel slow in Python, it usually is not because Python is hard. It is because of the learning approach.
Let me be direct.
β οΈ Avoid these habits
- Jumping between many tutorials
- Copying code without thinking
- Ignoring error messages
- Watching more than building
π Instead, build this discipline
- Follow one main learning path
- After every concept, write your own small code
- When an error appears, read it slowly
- Build small projects every week
π Python becomes easier the moment you start treating it like a tool, not a subject.
If you feel slow in Python, it usually is not because Python is hard. It is because of the learning approach.
Let me be direct.
β οΈ Avoid these habits
- Jumping between many tutorials
- Copying code without thinking
- Ignoring error messages
- Watching more than building
π Instead, build this discipline
- Follow one main learning path
- After every concept, write your own small code
- When an error appears, read it slowly
- Build small projects every week
π Python becomes easier the moment you start treating it like a tool, not a subject.
β€4
π§ Learn to Trace Code by Hand
Before running code, pause and predict the output. This builds real understanding.
Consider this:
Walk through slowly.
1. Start: x = 0
2. i = 0 β x = 0
3. i = 1 β x = 1
4. i = 2 β x = 3
Final output:
This habit strengthens your debugging ability more than passive reading ever will.
Try this daily with small snippets.
Before running code, pause and predict the output. This builds real understanding.
Consider this:
x = 0
for i in range(3):
x += i
print(x)
Walk through slowly.
1. Start: x = 0
2. i = 0 β x = 0
3. i = 1 β x = 1
4. i = 2 β x = 3
Final output:
3
This habit strengthens your debugging ability more than passive reading ever will.
Try this daily with small snippets.
β€5
Forwarded from Programming Quiz Channel
Which Python library is the most commonly used for numerical computing and matrix operations?
Anonymous Quiz
12%
Matplotlib
81%
NumPy
5%
Flask
2%
Seaborn