Hackforge Academy

Category: python

Mutable Default Problem

Published on 27 Oct 2026

Explanation

Default expressions are evaluated once when a function is defined, so a default list can retain values across calls.

Code:

def add_item(item, items=[]):
    items.append(item)
    return items
print(add_item('Python'))
print(add_item('Java'))

Explanation

Calls that omit a mutable parameter reuse the same default object, unintentionally sharing state.

Code:

def collect(value, values=[]):
    values.append(value)
    print(values)
collect(10)
collect(20)

Explanation

Use None as a default and create a new mutable object inside the function when needed.

Code:

def add_item(item, items=None):
    if items is None: items = []
    items.append(item)
    return items
print(add_item('Python'))
print(add_item('Java'))

Explanation

The same issue applies to dictionaries and sets; initialize them inside the function when fresh state is required.

Code:

def setting(key, value, values=None):
    if values is None: values = {}
    values[key] = value
    return values
print(setting('theme', 'dark'))

Explanation

If state should persist, model it explicitly using a closure or class rather than hiding it in a mutable default.

Code:

def accumulator():
    values = []
    def add(value):
        values.append(value)
        return list(values)
    return add
a = accumulator()
print(a(10), a(20))

πŸš€ Learn Spring Boot with real-world projects

πŸ’‘ Build REST APIs step by step

🧠 Improve backend development skills

🎯 Get career-ready practical training

Join Our Free WhatsApp Community

Direct access to niche-specific mentors and peers on WhatsApp.

🐍

Python Community

Discuss Django, FastAPI, AI integration, and automation scripts with 15k+ developers.

Join Python Community
βš›οΈ

React Community

Master Next.js, Framer Motion, and State Management. Share your latest UI components.

Join React Community
β˜•

Java Community

Deep dives into Spring Boot, Microservices architecture, and high-performance backend ops.

Join Java Community