Question 3: Modifying Lists in Python

This multiple-choice question tests the understanding of modifying lists in Python within a function. It assesses knowledge of list operations, function behavior, and variable scope.

What will be the output of the following code:

def modify_list(lst):
    lst.append(4)
    lst = lst + [5]
numbers = [1, 2, 3]
modify_list(numbers)
print(numbers)

Select an option:🤔🧐















C: is the correct answer.

In the modify_list function, the following operations occur:

  • lst.append(4): This appends the value 4 to the end of the list lst. After this operation, the list becomes [1, 2, 3, 4].
  • lst = lst + [5]: This concatenates lst with [5] and assigns the result to a new list lst. However, this assignment only modifies the local variable lst within the function scope. The original numbers list remains unchanged.

When numbers is printed outside the function, it still refers to the original list [1, 2, 3]. Hence, the output will be [1, 2, 3, 4].

Leave a Reply