Information about cookies on this page

Our website uses cookies to ensure the functionality of the website, to collect and analyze information about the performance and usage of the website. Privacy Policy

  • Courses
    • Discord
    • Twitter
    • Linkedin
    • Facebook
    • Instagram
  • Pricing
  • English
  • Čeština
  • Deutsch
  • Русский
Sign inStart free
  • Courses
  • Pricing

Community

Sign in
  
  • Courses
    • Discord
    • Twitter
    • Linkedin
    • Facebook
    • Instagram
  • Pricing
  • English
  • Čeština
  • Deutsch
  • Русский
Sign inStart free
  • Courses
  • Pricing

Community

Sign in

A List of Objects

In the lesson on dictionaries, you kept many pets in a list of dictionaries. A list can hold objects just as well. Each element is one pet, and a for loop goes through them one by one:

class Pet:
    def __init__(self, name, species, age):
        self.name = name
        self.species = species
        self.age = age

    def describe(self):
        return f"{self.name} is a {self.species}."

pets = [
    Pet("Rex", "dog", 3),
    Pet("Bella", "cat", 5),
    Pet("Kiwi", "parrot", 4)
]

for pet in pets:
    print(pet.describe())

names = [pet.name for pet in pets]
print(names)
Rex is a dog.
Bella is a cat.
Kiwi is a parrot.
['Rex', 'Bella', 'Kiwi']

The objects in the list don't need variables of their own: Pet("Bella", "cat", 5) creates a pet right in the list. In each iteration, pet holds one object, so pet.describe() calls the method on each pet in turn, and the list comprehension takes one attribute from each, pet.name.

Printing the whole list doesn't help: print(pets) shows <Pet object at 0x…> for each pet, even in a class with __str__. Print the pets one by one, in a loop.

To find the oldest pet, use max() with a key, as in the lesson on sorting. The key function gets one pet and returns what to compare, its age. Below the program above:

def by_age(pet):
    return pet.age

oldest = max(pets, key=by_age)
print(oldest.name)
for pet in sorted(pets, key=by_age):
    print(pet.name, pet.age)
Bella
Rex 3
Kiwi 4
Bella 5

max() returns the whole object, the pet with the largest age, not the age itself, so you can read any of its attributes. sorted() with the same key gives a new list of the pets, youngest first. Without a key, max(pets) ends with TypeError: '>' not supported between instances of 'Pet' and 'Pet': Python doesn't know how to compare two pets. (An instance is another word for an object made from a class.)

Instructions

  1. 1

    A year has gone by. Write a for loop that calls birthday() on every pet in the list and then prints the pet. The output should be Rex (dog, 4 years), Bella (cat, 6 years) and Kiwi (parrot, 5 years), each on its own line. Keep the lines of the list as they are.

  2. 2

    Write a key function by_age(pet) that returns the pet's age. Below the loop, use it with max() to print the oldest pet: Oldest: Bella (cat, 6 years).

Back

7/11

  1. 1. A Class and Its Objects
  2. 2. Attributes
  3. 3. Methods
  4. 4. Methods That Change the Object
  5. 5. Quiz: Objects
  6. 6. Printing an Object
  7. 7. A List of Objects
  8. 8. Inheritance
  9. 9. Quiz: Inheritance
  10. 10. super()
  11. 11. Summary
Next

Try it yourself

Do this exercise right here in your browser. No account needed.