How to Create a List of Objects in Python

avatar
Borislav Hadzhiev

Last updated: Apr 10, 2024
5 min

banner

# Table of Contents

  1. Create a list of objects in Python
  2. Append items to a List in a Class in Python

# Create a list of objects in Python

To create a list of objects:

  1. Declare a new variable and initialize it to an empty list.
  2. Use a for loop to iterate over a range object.
  3. Instantiate a class to create an object on each iteration.
  4. Append each object to the list.
main.py
class Employee(): def __init__(self, id): self.id = id list_of_objects = [] for i in range(5): list_of_objects.append(Employee(i)) print(list_of_objects) for obj in list_of_objects: print(obj.id) # ๐Ÿ‘‰๏ธ 0, 1, 2, 3, 4

create list of objects

The code for this article is available on GitHub

If you need to append items to a list in a class, click on the following subheading:

We used the range() class to get a range object we can iterate over.

The range() class is commonly used for looping a specific number of times in for loops.

main.py
print(list(range(5))) # ๐Ÿ‘‰๏ธ [0, 1, 2, 3, 4] print(list(range(1, 6))) # ๐Ÿ‘‰๏ธ [1, 2, 3, 4, 5]
If you need to start at a specific number, pass 2 arguments (start and stop) to the range() class.

On each iteration, we use the current number to create an instance of the Employee class and append the result to the list.

The list.append() method adds an item to the end of the list.

The Employee class can be instantiated with a single id argument, but you might have to pass more arguments when creating an object depending on your use case.

If you need to change the output of the print() function for the objects in the list, define the __repr__() method in the class.

main.py
class Employee(): def __init__(self, id): self.id = id def __repr__(self): return str(self.id) list_of_objects = [] for i in range(5): list_of_objects.append(Employee(i)) # ๐Ÿ‘‡๏ธ [0, 1, 2, 3, 4] print(list_of_objects)

We used the id of each object as the output of the print() function.

Note that the __repr__() method must return a string.

# Manually setting missing attributes

If your class doesn't define all of the necessary attributes in its __init__() method, use the setattr() function to add attributes to each object.

main.py
class Employee(): def __init__(self, id): self.id = id def __repr__(self): return str(self.id) list_of_objects = [] for i in range(3): obj = Employee(i) setattr(obj, 'topic', 'Python') setattr(obj, 'salary', 100) list_of_objects.append(obj) # ๐Ÿ‘‡๏ธ [0, 1, 2] print(list_of_objects) for obj in list_of_objects: print(getattr(obj, 'topic')) print(getattr(obj, 'salary'))

manually setting missing attributes

The code for this article is available on GitHub

The setattr() function adds an attribute to an object.

The function takes the following 3 arguments:

NameDescription
objectthe object to which the attribute is added
namethe name of the attribute
valuethe value of the attribute

The name string may be an existing or a new attribute.

The getattr function returns the value of the provided attribute of the object.

The function takes the object, the name of the attribute and a default value for when the attribute doesn't exist on the object as parameters.

Alternatively, you can use a list comprehension.

# Create a list of objects using a list comprehension

This is a three-step process:

  1. Use a list comprehension to iterate over a range object.
  2. On each iteration, instantiate a class to create an object.
  3. The new list will contain all the newly created objects.
main.py
class Employee(): def __init__(self, id): self.id = id def __repr__(self): return str(self.id) list_of_objects = [ Employee(i) for i in range(1, 6) ] print(list_of_objects) # ๐Ÿ‘‰๏ธ [1, 2, 3, 4, 5] for obj in list_of_objects: print(obj.id) # 1, 2, 3, 4, 5
The code for this article is available on GitHub

We used a list comprehension to iterate over a range object with a length of 5.

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 instantiate the Employee class to create an object and return the result.

The new list contains all of the newly created objects.

Which approach you pick is a matter of personal preference.

List comprehensions are quite direct and easy to read, but you'd have to use a for loop if you need to add additional attributes to each object or the creation process is more involved.

# Append items to a List in a Class in Python

To append items to a list in a class:

  1. Initialize the list in the class's __init__() method.
  2. Define a method that takes one or more items and appends them to the list.
main.py
class Employee(): def __init__(self, name, salary): self.name = name self.salary = salary self.tasks = [] # ๐Ÿ‘ˆ๏ธ initialize list def add_task(self, task): self.tasks.append(task) return self.tasks bob = Employee('Bobbyhadz', 100) bob.add_task('develop') bob.add_task('ship') print(bob.tasks) # ๐Ÿ‘‰๏ธ ['develop', 'ship']
The code for this article is available on GitHub

We initialized the tasks list as an instance variable in the class's __init__() method.

Instance variables are unique to each instance you create by instantiating the class.

main.py
class Employee(): def __init__(self, name, salary): self.name = name self.salary = salary self.tasks = [] # ๐Ÿ‘ˆ๏ธ initialize list def add_task(self, task): self.tasks.append(task) return self.tasks alice = Employee('Alice', 1000) alice.add_task('design') alice.add_task('test') print(alice.tasks) # ๐Ÿ‘‰๏ธ ['design', 'test'] bob = Employee('Bobbyhadz', 100) bob.add_task('develop') bob.add_task('ship') print(bob.tasks) # ๐Ÿ‘‰๏ธ ['develop', 'ship']

The two instances have separate tasks lists.

You can also use class variables instead of instance variables.

Class variables are shared by all instances of the class.

main.py
class Employee(): # ๐Ÿ‘‡๏ธ class variable tasks = [] def __init__(self, name, salary): self.name = name self.salary = salary @classmethod def add_task(cls, task): cls.tasks.append(task) return cls.tasks Employee.add_task('develop') Employee.add_task('ship') print(Employee.tasks) # ๐Ÿ‘‰๏ธ ['develop', 'ship'] alice = Employee('Alice', 1000) print(alice.tasks) # ๐Ÿ‘‰๏ธ ['develop', 'ship'] bob = Employee('Bobbyhadz', 100) print(bob.tasks) # ๐Ÿ‘‰๏ธ ['develop', 'ship']
The code for this article is available on GitHub

The tasks variable is a class variable, so it is shared by all instances.

We marked the add_task() method as a class method. The first argument class methods get passed is the class.

The list.append() method adds an item to the end of the list.

However, something you might often have to do is append multiple items to the list.

# Append multiple items to a list in a class

You can use the list.extend() method to append the items of an iterable to a list.

main.py
class Employee(): def __init__(self, name, salary): # ๐Ÿ‘‡๏ธ instance variables (unique to each instance) self.name = name self.salary = salary self.tasks = [] # ๐Ÿ‘ˆ๏ธ initialize list def add_tasks(self, iterable_of_tasks): self.tasks.extend(iterable_of_tasks) return self.tasks bob = Employee('Bobbyhadz', 100) bob.add_tasks(['develop', 'test', 'ship']) print(bob.tasks) # ๐Ÿ‘‰๏ธ ['develop', 'test', 'ship']
The code for this article is available on GitHub

We used the list.extend() method to append multiple values to the tasks list.

The list.extend() method takes an iterable (such as a list or a tuple) and extends the list by appending all of the items from the iterable.

# Additional Resources

You can learn more about the related topics by checking out the following tutorials:

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.

Copyright ยฉ 2024 Borislav Hadzhiev