Question

1.
2.
3.
4.
Answer (Detailed Solution Below)

Option 1 : [1] on the first line and [1, 2] on the second / पहली पंक्ति में [1] और दूसरी में [1, 2]

Advertisement

Detailed Solution

सही उत्तर [1] on the first line and [1, 2] on the second / पहली पंक्ति में [1] और दूसरी में [1, 2] है।

Key Points
Helpful?
PrepSnapprepsnap.in • Part -A

Question:

What does the following Python code with a mutable default argument output? / परिवर्तनीय डिफ़ॉल्ट तर्क वाले निम्नलिखित Python कोड का आउटपुट क्या है? def add(item, bag=[]): bag.append(item) return bag print(add(1)) print(add(2))

1.
[1] on the first line and [1, 2] on the second / पहली पंक्ति में [1] और दूसरी में [1, 2]
2.
[1] on the first line and [2] on the second / पहली पंक्ति में [1] और दूसरी में [2]
3.
[1, 2] on both lines / दोनों पंक्तियों में [1, 2]
4.
Error / त्रुटि

Correct Answer: [1] on the first line and [1, 2] on the second / पहली पंक्ति में [1] और दूसरी में [1, 2]

The default list is created once and shared across calls, so the second call appends to the same list: [1] then [1, 2]. This classic mutable-default-argument trap is why option (b) tempts. / डिफ़ॉल्ट सूची एक बार बनती है और सभी कॉल में साझा होती है, इसलिए दूसरी कॉल उसी सूची में जोड़ती है: पहले [1] फिर [1, 2]।

Downloaded from PrepSnap (prepsnap.in)