Python Default Argument Evaluation

Python: The "Mutable Default" Trap Topic: Function Definitions & Memory Difficulty: Intermediate Question: What is the output of the final line of this code? def add_item(item, box=[]): box.append(item) return box print(add_item("Apple")) print(add_item("Banana")) A) ['Apple'] then ['Banana'] B) ['Apple'] then ['Apple', 'Banana'] C) ['Apple'] then Error: box is not defined D) ['Banana'] then ['Banana'] Did you know Python evaluates default arguments only once at the time of function definition? If you chose B, you understand why we usually use box=None instead!

To view or add a comment, sign in

Explore content categories