Python Function Puzzle: Default Argument Behavior

Can you predict the output of this classic Python function puzzle? 🐍 ```python def add_to_list(val, my_list=[]): my_list.append(val) return my_list print(add_to_list(1)) print(add_to_list(2)) ``` What's the output? A) [1], [2] B) [1], [1, 2] C) [1, 2], [1, 2] D) [1, 2], [3] Comment your answer and share your explanation! #Python #Coding #Programming #Quiz #LinkedIn

B---Default arguments in Python are evaluated once at function definition time, so mutable defaults like lists are shared across calls.

Like
Reply

To view or add a comment, sign in

Explore content categories