Subjects

All subjects Django Java Python React Spring Boot JavaScript PHP
Sign Up Free
Question 6 of 10 · Python Basics & Syntax
Interview question

What is the difference between mutable and immutable objects in Python? Python में mutable और immutable objects में क्या अंतर है?

Answer
MutableImmutable
list, dict, setint, float, str, tuple, frozenset, bool
Can be changed in placeCannot 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
MutableImmutable
list, dict, setint, 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 items

Was this answer clear?