Sobes.tech
Middle

x = [1, 2, 3]; y = x; y.append(4) What will happen?

sobes.tech AI

Answer from AI

In this code:

x = [1, 2, 3]
y = x
y.append(4)

the variable y refers to the same list as x. The append method modifies the list in place, adding the element 4 to the end.

As a result, both x and y will point to the list [1, 2, 3, 4].

That is, after executing the code:

print(x)  # [1, 2, 3, 4]
print(y)  # [1, 2, 3, 4]

This is because lists in Python are mutable objects, and the assignment y = x does not create a copy but only a new reference to the same object.