What is the expected output of the following code?

What is the expected output of the following code?

def func(p1, p2):

p1 = 1

p2[0] = 42

x = 3

y = [1, 2, 3]

func(x, y)

print(x, y[0])
A . 3 1
B. The code is erroneous.
C. 1 42
D. 3 42
E. 1 1

Answer: D

Explanation:

Topics: def list argument passing mutable vs. immutable

Try it yourself:

def func(p1, p2):

p1 = 1

p2[0] = 42

x = 3

y = [1, 2, 3]

func(x, y)

print(x, y[0]) # 3 42

This question is about argument passing.

It is a big difference, whether you pass a mutable or an immutable data type.

The immutable integer in x gets copied to p1

and the change of p1 does not effect x

The mutable list in y gets referenced to p2

and the change of p2 effect y

Subscribe
Notify of
guest
0 Comments
Inline Feedbacks
View all comments