Print a list of class objects in Python

avatar

Borislav Hadzhiev

Last updated: Sep 11, 2022

banner

Photo from Unsplash

Print a list of class objects in Python #

Define the __repr__() method on the class to print a list of class objects. The __repr__() method is called by the repr() function and will get called for each object in the list.

main.py
class Employee(): def __init__(self, name, salary): self.name = name self.salary = salary def __repr__(self): return self.name alice = Employee('Alice', 100) print(alice) # 👉️ Alice bob = Employee('Bobbyhadz', 100) print(bob) # 👉️ Bobbyhadz result = [alice, bob] print(result) # 👉️ [Alice, Bobbyhadz]

We defined the __repr__() method to print a list of class objects.

The __repr__ method is called by the repr() function and is usually used to get a string that can be used to rebuild the object using the eval() function.

Make sure to return a string from the __repr__() method, otherwise a TypeError is raised.

If you need to return an integer, use the str() class to convert it to a string.

main.py
class Employee(): def __init__(self, name, salary): self.name = name self.salary = salary def __repr__(self): return str(self.salary) # 👈️ convert to string alice = Employee('Alice', 100) print(alice) # 👉️ Alice bob = Employee('Bobbyhadz', 100) print(bob) # 👉️ Bobbyhadz result = [alice, bob] print(result) # 👉️ [Alice, Bobbyhadz]

An alternative approach is to access an attribute on each item in the list and print the result.

main.py
class Employee(): def __init__(self, name, salary): self.name = name self.salary = salary alice = Employee('Alice', 100) bob = Employee('Bobbyhadz', 100) result = [alice, bob] # 👇️ ['Alice', 'Bobbyhadz'] print([obj.name for obj in result])

Notice that we didn't define a __repr__() method.

We used a list comprehension to iterate over the list of objects.

List comprehensions are used to perform some operation for every element or select a subset of elements that meet a condition.

On each iteration, we access the name attribute on the object and return the result.

The last step is to pass the list to the print() function.

I wrote a book in which I share everything I know about how to become a better, more efficient programmer.
book cover
You can use the search field on my Home Page to filter through all of my articles.