'Python Changes Object Data Inside List Syncronously With The Related Object

class RandomData:



def __init__(self):

    self.id=0

def rand_prod(self):


    self.id+=1

    self.name,self.surname=unique_names_generator.get_random_name().split()

    self.address=real_random_address()

    self.birthday=datetime.date(randint(1950,2021),randint(1,12),randint(1,28))

    self.latitude=(18,16)

    self.longtitude=(18,16)



data_list=[]

current_rd=RandomData()

for i in range(5):

     current_rd.rand_prod()
     data_list.append(current_rd.__dict__)

I create a RandomData object and call the rand_prod() method inside the for loop, and in the loop I append this data to a list by saying objectname.dict, but when I print the last list, all 5 dicts in the list have the data obtained in the last for loop. Every time I change the properties of the object, the old properties that I previously added in the list also change. What is the reason for this and how can I solve it?



Solution 1:[1]

You should really make a new object each time round the loop.

data_list=[]

for i in range(5):
     current_rd=RandomData()
     current_rd.rand_prod()
     data_list.append(current_rd.__dict__)

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 quamrana