Python coding challenge - Day 2 | Output Prediction MCQ

  What Is the Output of This Python Code?



Question :

a = [10, 20, 30] b = a b.append(40) print(a)

Options :

A) [10, 20, 30]

B) [10, 20, 30, 40]

C) [40]

D) Error


Correct Answer :

B) [10, 20, 30, 40]


Explanation :

First we create a list :

a = [10, 20, 30]

The list contains 3 elements.

[10, 20, 30]

Step 1 - Assignment

Now look at this line :

b = a

Important point :

This does not create a new list.

Instead b refers to the same list as a.

Both variables point to the same object in memory.


Step 2 - append()

Now this line executes :

b.append(40)

append()adds the value 40 to the list.

Since a and b refer to the same list, the change affects both variables.


Step 3 - New List

The list becomes :

[10, 20, 30, 40]

Elements are now :

1 → 10
2 → 20
3 → 30
4 → 40

Total elements = 4


Step 4 - print()

print(a)

Even though we modified b, the change appears in a because both refer to the same list.


Output :

[10, 20, 30, 40]

Practice daily Python coding challenges to improve your programming and logical thinking skills.

No comments:

Post a Comment