How to Create Lists of Objects and Append Items to Lists in Classes in Python
This guide explores how to create lists of objects and manage lists within Python classes. We'll cover instantiation, appending to lists within the class and using class variables vs instance variables when working with lists. You'll learn practical techniques for creating and managing collections of objects in your Python code.
Creating a List of Objects
You can create a list of objects by instantiating a class in a loop and appending the results to a list.
1. Using a for Loop
The most straightforward approach is to use a for loop with the range() function to create a sequence and then instantiate the class and append the result to the list:
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)
Output
[<__main__.Employee object at 0x7f46887a4f10>, <__main__.Employee object at 0x7f46887a4fa0>, <__main__.Employee object at 0x7f46887d0430>, <__main__.Employee object at 0x7f46887380a0>, <__main__.Employee object at 0x7f4688738250>]
0
1
2
3
4
- The
forloop iterates five times, creating fiveEmployeeobjects, appending the object tolist_of_objectsin every iteration. - Then the code loops over the list of objects and prints the id of each object.
To control how the object is printed, it's important to implement the __repr__ method in your class. This ensures that the objects will be displayed in a clear, user-friendly format.
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))
print(list_of_objects) # Output: [0, 1, 2, 3, 4]
Also, you can dynamically set attributes to the object using the setattr() function:
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)
print(list_of_objects)
for obj in list_of_objects:
print(getattr(obj, 'topic'))
print(getattr(obj, 'salary'))
Output:
[0, 1, 2]
Python
100
Python
100
Python
100
- The
setattr()function can be used to add new or modify existing attributes dynamically to an object.
2. Using a List Comprehension
You can also use a list comprehension to create a list of objects in a more concise manner:
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) # Output: [1, 2, 3, 4, 5]
for obj in list_of_objects:
print(obj.id)
Output:
1
2
3
4
5
- The list comprehension
[Employee(i) for i in range(1, 6)]creates a list where each element is the result of instantiating theEmployeeclass.
Appending Items to a List in a Class
When you need a list associated with your class, you can initialize it and manage it in the class itself.
1. Using Instance Variables
Instance variables are unique to each instance of a class. This means, each object will have it's own independent copy of the list. Use the append() method to add single items to the list.
class Employee():
def __init__(self, name, salary):
self.name = name
self.salary = salary
self.tasks = [] # Instance variable initialized as an empty list
def add_task(self, task):
self.tasks.append(task)
return self.tasks
tom = Employee('Tom', 100)
tom.add_task('develop')
tom.add_task('ship')
print(tom.tasks) # Output: ['develop', 'ship']
alice = Employee('Alice', 1000)
alice.add_task('design')
alice.add_task('test')
print(alice.tasks) # Output: ['design', 'test']
Output:
['develop', 'ship']
['design', 'test']
- In the
__init__()method, the instance variableself.tasksis initialized to an empty list. - The
add_task()method uses theappend()method to add new items to theself.taskslist, and returns the list. - Each employee object will have it's own, independent list of tasks.
2. Using Class Variables
Class variables are shared by all instances of the class. Use class methods to append items to class variables.
class Employee():
tasks = [] # Class variable
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)
alice = Employee('Alice', 1000)
print(alice.tasks)
tom = Employee('Tom', 100)
print(tom.tasks)
Output:
['develop', 'ship']
['develop', 'ship']
['develop', 'ship']
- Class variable
tasksis declared on the class, not on a specific object. - Class methods are created using the
@classmethoddecorator. The first argument in the method isclswhich refers to the class. - When class method
add_task()is called, it appends the tasks to thetasksvariable which is a list on the class. - All of the instances will refer to the same
taskslist which is on the class.
Appending Multiple Items with extend()
To append multiple items from an iterable to a list, use the extend() method in the class:
class Employee():
def __init__(self, name, salary):
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
tom = Employee('TomNolan', 100)
tom.add_tasks(['develop', 'test', 'ship'])
print(tom.tasks) # Output: ['develop', 'test', 'ship']
- The
extend()method appends all items from the given iterable to the list.