What is the expected output of the following code?

What is the expected output of the following code?

list1 = [1, 3]

list2 = list1

list1[0] = 4

print(list2)
A . [1, 4]
B. [4, 3]
C. [1, 3, 4]
D. [1, 3]

Answer: B

Explanation:

Topics: list reference of a mutable data type

Try it yourself:

list1 = [1, 3]

list2 = list1

list1[0] = 4

print(list2) # [4, 3]

print(id(list1)) # e.g. 140539383947452

print(id(list2)) # e.g. 140539383947452 (the same number)

A list is mutable.

When you assign it to a different variable, you create a reference of the same object.

If afterwards you change one of them, the other one is changed too.

Subscribe
Notify of
guest
0 Comments
Inline Feedbacks
View all comments