Interview question
What is the difference between mutable and immutable objects in Python? Python में mutable और immutable objects में क्या अंतर है?
Answer
| Mutable | Immutable |
|---|---|
| list, dict, set | int, float, str, tuple, frozenset, bool |
| Can be changed in place | Cannot be changed after creation |
# Mutable - list changes in place, same object id
my_list = [1, 2, 3]
print(id(my_list))
my_list.append(4)
print(id(my_list)) # SAME id - modified in place
# Immutable - string 'change' actually creates a NEW object
s = 'hello'
print(id(s))
s = s + ' world'
print(id(s)) # DIFFERENT id - new string object created
# Common gotcha: mutable default arguments
def add_item(item, items=[]): # DANGEROUS - default list is shared across calls!
items.append(item)
return items
print(add_item('a')) # ['a']
print(add_item('b')) # ['a', 'b'] - unexpected! Same default list reused
# Fix - use None as default, create new list inside
def add_item_safe(item, items=None):
if items is None:
items = []
items.append(item)
return items| Mutable | Immutable |
|---|---|
| list, dict, set | int, float, str, tuple |
| जगह पर बदल सकते हैं | Creation के बाद बदल नहीं सकते |
my_list = [1, 2, 3]
print(id(my_list))
my_list.append(4)
print(id(my_list)) # SAME id
s = 'hello'
print(id(s))
s = s + ' world'
print(id(s)) # अलग id - नया object
# Common gotcha: mutable default arguments
def add_item(item, items=[]): # खतरनाक!
items.append(item)
return items
print(add_item('a')) # ['a']
print(add_item('b')) # ['a', 'b'] - अनपेक्षित!
# Fix
def add_item_safe(item, items=None):
if items is None:
items = []
items.append(item)
return itemsWas this answer clear?