edited by
558 views
1 1 vote

Consider the given Python program.

def append_to_lst(val, lst=[]):
    lst.append(val)
    return lst
print(append_to_lst(1))
print(append_to_lst(2))
print(append_to_lst(3, []))

Which of the following is the correct output of this program?

  1. $\begin{array}{l}{[1]} \\ {[2]} \\ {[3]}\end{array}$
  2. $\begin{array}{l}{[1]} \\ {[1,2]} \\ {[3]}\end{array}$
  3. $\begin{array}{l}{[1]} \\ {[2]} \\ {[1,2,3]}\end{array}$
  4. $\begin{array}{l}{[1]} \\ {[1,2]} \\ {[1,3]}\end{array}$

1 Answer

1 1 vote
Remember:

 

In Python, default arguments are evaluated only once at the time of function definition.  

If the default argument is mutable (like a list), the same object is reused across function calls.

 

 

First call:
\[
\texttt{append_to_lst(1)} \rightarrow [1]
\]

Second call (same default list reused):
\[
\texttt{append_to_lst(2)} \rightarrow [1, 2]
\]

Third call (new empty list passed explicitly):
\[
\texttt{append_to_lst(3, [])} \rightarrow [3]
\]

 

Final Output:
\[
[1]
\]
\[
[1, 2]
\]
\[
[3]
\]

 

Hence, the correct option is:
\[
{(B)}
\]
moved by
Answer:
Position:
Show:

Related questions

0 0 votes
1 1 answer
743
743 views
gatecse asked Feb 23
743 views
Consider the given Python program.def fun(L, i=0): if i >= len(L)-1: return 0 if L[i] L[i+1]: L[i+1], L[i] = L[i], L[i+1] return 1+fun(L, i+1) else: return fun(L, i+1) d...
2 2 votes
5 5 answers
848
848 views
gatecse asked Feb 23
848 views
​​​​​​A recursive function in Python is given.def mystery(n): if n <= 0: return 1 else: return mystery(n-1) + mystery(n-2)Now, consider the following function call:myster...
0 0 votes
1 1 answer
536
536 views
gatecse asked Feb 23
536 views
Consider the given Python program.def outer(): x = [] def inner(val): x.append(val) return x return inner f1 = outer() f2 = outer() print(f1(10)) # Line P print(f1(20)) #...
5 5 votes
1 1 answer
364
364 views
GO Classes asked Jul 1
364 views
Consider the following Python code:def virfib_sq(n): print(n) if n <= 1: return n return (virfib_sq(n - 1) + virfib_sq(n - 2)) 2 r4 = virfib_sq(4)What would be the outp...