Posts

Showing posts from January, 2026

Identity vs Equality in Python

 This topic is extremely important if you are learning Python as a beginner.  Golden Rule == → compares values is → compares memory identity Example 1: In the following example, even though values are the same , a and b are different objects in memory . a = [1, 2, 3] b = [1, 2, 3] print(a == b)  # True print(a is b)  # False Example 2: In this example, a and b are equal and as well as identical. This is because Python reuses small integers to optimize memory usage which is known as  Integer Interning . a = 256 b = 256 print(a == b) # False print(a is b)  # True Example 3: The same logic applies to string values since Python reuses small string values to optimize memory usage as well. a = "hello" b = "hello" print(a is b)  # True Example 4: In the following example, the values are equal  but they are different objects . a = "".join(["he", "llo"]) b = "hello" print(a is b)  # False

Mutable Default Arguments (A Common Python Bug)

One of the most common mistakes Python developers make is using mutable objects as default function arguments. In this following example, the default list items=[] is used as the function argument. When mutable object - list is used as function argument, the object is created once and reused  every time the function is called. This creates hidden persistent storage , where data keeps accumulating across calls. def add_items(item, items=[] ):     items.append(item)     return items print(add_items(1)) print(add_items(2)) Output [1] [1, 2] "Mutable objects should not be used as default function arguments. Instead, use None  and create the object inside the function." In this way, each function call now creates a fresh new list . def add_items(item, items= None ):     if items is None:         items = []     items.append(item)     return items print(add_items(1)) print(add_items(2)) Output [1] [2]

Python Internals - Mutable vs Immutable Objects

  Understanding Python internals is   crucial for writing bug-free code   and is a   favorite topic in technical interviews . On Day 1, we focus on how Python handles objects in memory, mutability, function arguments, and object identity. Let’s break it down step by step. 1. Mutable vs Immutable Objects in Python In Python,  everything is an object , and each object is either  mutable  or  immutable . 1a. Immutable Objects Immutable objects  cannot be changed after creation . Examples: int float str tuple and frozenset Example: Input a = 10 b = a b += 1 print(a) Output - 10 🧠  This is because   int  is immutable. When  b += 1  is executed, Python creates a  new object  for  b . a  still points to the original value  10 . 1b. Mutable Objects Mutable objects  can be modified in place . Examples: list dict set and  Most Custom Objects Example: Input a = [1, 2, 3] b = a b.append(4) prin...