Sobes.tech
Middle+

Look at the code: there is a list lst, which is modified via append, and a variable res. Why do lst == res and lst is res both return True?

sobes.tech AI

Answer from AI

In Python, lists are mutable objects, and when you assign a list lst to a variable res, both variables refer to the same object in memory.

The append method modifies the list in place without creating a new object. Therefore, after calling lst.append(...), both lst and res point to the same modified list.

Hence:

  • lst == res returns True because the contents of the lists are the same.
  • lst is res returns True because both variables refer to the same object.

Example:

lst = [1, 2, 3]
res = lst
lst.append(4)
print(lst == res)  # True
print(lst is res)  # True

If you want res to be a copy of the list, you should use copying methods, for example res = lst.copy().

Look at the code: there is a list lst, which is… - sobes.tech