Day 4: Using Mutable Default Arguments
Using mutable objects as default arguments is one of the most common and dangerous Python mistakes.
❌ The Mistake
❗ Unexpected Output
❌ Why this fails?
Because default arguments are evaluated only once, not every time the function is called.
The list [] is created a single time and then shared across all function calls.
Each call modifies the same list.
✅ The Correct Way
Use None as the default value and create the list inside the function.
✔ Correct Output
๐ง Simple Rule to Remember
-
❌ Never use mutable objects (list, dict, set) as default arguments
-
✅ Use None and initialize inside the function
✅ Key Takeaway
Default arguments in Python are shared, not recreated.
This can cause unexpected behavior if you’re not careful.


0 Comments:
Post a Comment