Python · Question 14 · Hard

What will be the output of the following Python code?

def add(x, lst=[]):
    lst.append(x)
    return lst

add(1)
print(add(2))
  1. [1, 2]
  2. [2]
  3. [1]
  4. [2, 1]
Answer and explanation

Answer: A. [1, 2]

Explanation: The default list is created once, when the function is defined, and is reused on every call that omits lst. The first call leaves [1] in it, so the second call returns [1, 2].

Previous: What will be the output of the following Python code? · Next: What will be the output of the following Python code?

Practise python

Try a fresh set of python questions with an explanation after every answer, free and without signing up: Python practice. Or sit a full placement mock test.

More python questions

More technical & programming practice

Data Structures · Algorithms · Object-Oriented Programming · DBMS · SQL · Operating Systems · Computer Networks · Software Engineering

LogicWiz Exams home · All practice topics · Placement mock tests · Daily 10 challenge