Consider the following example:
class Test:
def __init__(self, lis: list):
self.list = lis
lis = [1, 2, 3]
obj1 = Test(lis)
obj2 = Test(lis)
print(obj1 is obj2)
print(obj1.list is obj2.list)
obj1.list.reverse()
print(obj2.list)
Output :
False
True
[3, 2, 1]
Explanation:
I create 2 objects of the same class,and the "list" of each object is [1, 2, 3]
. Testing if the names obj1
,obj2
are referencing the same object the answer is negative (False). But when I test if obj1.list is obj2.list
, we get 'True
' as an answer.Thus when I reverse the list of the name obj1
,the list is also reversed of the name obj2
, because it is the same list for both names.
What I need is a way to reverse the list for obj1
, but not for obj2
. So I need to create a new list.
In the end,this will be the result:
obj1.list.reverse()
print(obj2.list)
Expected output:
[1, 2, 3]