Welcome to the Treehouse Community

Want to collaborate on code errors? Have bugs you need feedback on? Looking for an extra set of eyes on your latest project? Get support with fellow developers, designers, and programmers of all backgrounds and skill levels here with the Treehouse Community! While you're at it, check out some resources Treehouse students have shared here.

Looking to learn something new?

Treehouse offers a seven day free trial for new students. Get access to thousands of hours of content and join thousands of Treehouse students and alumni in the community today.

Start your free trial

Python

David Ellis
David Ellis
2,252 Points

How do I make a list from instances of a class

Hi,

I am having a play with classes. What would the simplest method be to create a list from instances in a class. I think it involves .append. I would like to use the list I create outside of the class.

ie.. can I create:

horse_list = [] 

somewhere in the class, then:

horse_list.append(self)

in the __init__ function somewhere?

My code is below:

class Horse:

    def __init__(self, name, odds):
        self.name = name
        self.odds = odds


horse_a = Horse('Boris', 9)
horse_b = Horse('Trevor', 8)
horse_c = Horse('Nigel', 7)
horse_d = Horse('Clive', 6)

1 Answer

Chris Freeman
MOD
Chris Freeman
Treehouse Moderator 68,441 Points

Since the list containS instances of Horse, the list construction would occur outside the class. Perhaps a list comprehension would word;

horse_info = [
    ('Boris', 9), 
    ('Trevor', 8), 
    ('Nigel', 7), 
    ('Clive', 6)
]

horses = [Horse(*info) for info in horse_info]

Post back if you need more help. Good luck!!!

David Ellis
David Ellis
2,252 Points

Thankyou Chris, That code worked :)