Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

How to create a list of objects from with values from another list of values?

I’m trying to create a list of objects that hold a list themselves. I’m creating this from another list of elements.

class Test():
    temp_list = list()


x = [['a','b','c'],['g','f','h']]

list_of_obj = list()

for i in x:
    test = Test()
    for b in i:
        test.temp_list.append(b)
    list_of_obj.append(test)

for obj in list_of_obj:
    print(obj)

The idea in the above code is to split the list of lists (x) into 2 objects that hold all their elements.

However, when I print the temp_list in the objects, both lists have all the elements in x.

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

OUTPUT

['a', 'b', 'c', 'g', 'f', 'h']
['a', 'b', 'c', 'g', 'f', 'h']

Expected Output

['a', 'b', 'c']
['g', 'f', 'h']

>Solution :

This is because temp_list is a class attribute. Class attributes are not unique to instances of the class . They are universal to all instances.

What you want to do is create and instance attribute for temp_list Like this:

class Test():
    def __init__(self):
        self.temp_list = []
...

Per Random Davis suggestion in the comments:
If you want to be able to print the class directly you should also add this method to your class.

    def __str__(self):
        return str(self.temp_list)
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading