310 views
1 1 vote

Consider the following Python code:

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, []))

What will be the output?

  1. $\verb|[1]|$
    $\verb|[2]|$
    $\verb|[3]|$
     
  2. $\verb|[1]|  $
    $\verb|[1, 2]|  $
    $\verb|[3]|$
     
  3. $\verb|[1]|  $
    $\verb|[2]|  $
    $\verb|[1, 2, 3]|$
     
  4. $\verb|[1]|  $
    $\verb|[1, 2]|  $
    $\verb|[1, 2, 3]|$

1 Answer

1 1 vote

Answer: B

 

The key to this problem is understanding how default arguments are handled in Python. When lst=[] is used as a default argument, the same list object is created only once when the function is defined, not every time the function is called. Subsequent calls to the function without providing a new list will reuse and modify this single, shared list object. 

  1. The first call, append_to_lst(1), uses the default list. The list becomes [1], and [1] is printed.
  2. The second call, append_to_lst(2), again uses the same default list object. The value 2 is appended to the existing list, making it [1, 2], and [1, 2] is printed.
  3. The third call, append_to_lst(3, []), explicitly provides a new, empty list ([]) as an argument. The value 3 is appended to this new list, making it [3], and [3] is printed.

The output will therefore be:

[1]
[1, 2]
[3]

 

Answer:
Position:
Show:

Related questions

1 1 vote
0 0 answers
235
235 views
GO Classes asked Feb 17
235 views
Let $G=(V,E)$ be a directed graph, and let $G^R$ denote the graph obtained by reversing all the edges of $G$.Which of the following statements is/are TRUE?If a vertex $v$...
0 0 votes
2 2 answers
296
296 views
GO Classes asked Feb 17
296 views
A binary tree has the following traversals:Preorder traversal$: P, Q, S, E, R, F, G$ Inorder traversal$: S, Q, E, P, F, R, G$ Which of the following statement(s) is/are T...
0 0 votes
1 1 answer
237
237 views
GO Classes asked Feb 17
237 views
Consider the following Python code:def outer(): x = [] def inner(val): x.append(val) return x return innerNow consider:f1 = outer() f2 = outer...
1 1 vote
2 2 answers
326
326 views
GO Classes asked Feb 17
326 views
Consider the following function:def fun(L, i = 0): if i >= len(L) - 1: return 0 if L[i] L[i + 1]: L[i], L[i + 1] = L[i + 1], L[i] return ...