PyCodeItPython trace & interview prep
DashboardMastery MapSQL PracticeDailyInterviewBlogLeaderboardCommunity

Loading PyCodeIt workspace...

PyCodeIt

Free interactive learning platform for Python code tracing, SQL queries, and technical interviews. Built for bootcamp grads, computer science students, and engineers.

Python Practice

  • Learning Center
  • For loop tracing
  • List tracing
  • Dictionary tracing
  • Decorators practice
  • Python Tracing Guide
  • Python Output Questions

SQL Practice

  • SQL Fundamentals
  • Relational JOINs
  • Window Functions
  • CTEs & Set Operators
  • SQL JOINs Guide
  • Window Functions Guide

Legal

  • About
  • Contact
  • Privacy Policy
  • Terms of Service

© 2026 PyCodeIt 2026. All rights reserved.

Mutable Default Arguments - Why they surprise you

This example shows why using a mutable object as a default argument causes shared state across calls. We include a step-by-step trace table and a production-safe fix.

def append_to(element, target=[]):
    target.append(element)
    return target

print(append_to(1))
print(append_to(2))

Trace walkthrough

  1. At function definition time, Python creates the default list object: list_ref_1 = []
  2. First call: append_to(1) uses target = list_ref_1, appends 1, returns [1]
  3. Second call: append_to(2) again uses target = list_ref_1 (same object), appends 2, returns [1,2]

Correct pattern

def append_to(element, target=None):
    if target is None:
        target = []
    target.append(element)
    return target

Use `None` as the default and create the mutable inside the function to avoid accidental shared state. This is the recommended production pattern.

Companion video:
Mutable Default Arguments in Python - concise explainer
Timestamps: 00:00 Problem statement · 01:10 Demonstration · 02:40 Fix patterns
Return to Practice