Post

Python Programming
Python Programming@PythonPr·
Python Question / Quiz; What is the output of the following Python code, and why? Comment your answers below!
Python Programming tweet media
English
20
13
85
12.8K
Jenny
Jenny@JennyTheDev·
D. [1, 2] The classic Python trap. Default list b=[] is created ONCE when the function is defined, not on each call. So func(1) appends 1 → [1] Then func(2) appends to the SAME list → [1, 2] This is why you always use b=None and then b = b or [] inside the function. Every Python dev learns this the hard way exactly once 😂
English
0
0
8
964
Earnest Codes
Earnest Codes@Earnesto037·
@PythonPr The correct answer is [1] [1, 2] Why does this happen? The trick lies in how Python handles default arguments. Here is the breakdown: Persistent Objects: Default arguments are evaluated only once at the time the function is defined, not every time the function is called.
English
1
0
5
996
Jay
Jay@learnaiwthme·
Answer: D) [1, 2] Because the default argument is mutable and shared across function calls. The list is created when the function is defined, not when it is called. Each call appends to the same list, so values accumulate over time. This is why mutable default arguments should be avoided in Python.
English
0
0
2
181
Terrence
Terrence@terrenceeleven·
@PythonPr None of the above. [ 1 ] [ 1 , 2 ] Default list persist across calls Def functions.😂 .@PythonPr
English
0
0
2
125
PyBerry Tech 🐍🍓
PyBerry Tech 🐍🍓@PyBerryTech·
@PythonPr Option D : [1, 2] Python’s default arguments are evaluated once, not each call. The list b is shared across calls. First call appends 1. Second call reuses the same list and appends 2, so it becomes [1, 2]. Sneaky, but totally Pythonic! 🐍🍓
English
0
0
1
571
하오리 🦆📒
하오리 🦆📒@haori_notes·
D. [1, 2] This is because default arguments in Python are only created once — when the function is defined, not each time it's called. So the list b=[] is shared across all calls to the function. Here's what happens: func(1) → appends 1 to b, so b becomes [1] func(2) → reuses the same list, appends 2 → b is now [1, 2]
English
0
0
1
51
Tanmay Newatia
Tanmay Newatia@thetanmaydoes·
@PythonPr C: [1] [2] as the function has a default parameter b as empty list (i.e. []), and func is being called with a single param (i.e. a), being passed as 1 in first call, and 2 in second call, it would be added to the empty list and returned.
English
0
0
1
345
Paylaş