Last updated: Apr 10, 2024
Reading timeยท5 min
To create a list of objects:
for
loop to iterate over a range
object.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
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.
print(list(range(5))) # ๐๏ธ [0, 1, 2, 3, 4] print(list(range(1, 6))) # ๐๏ธ [1, 2, 3, 4, 5]
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.
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.
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.
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'))
The setattr() function adds an attribute to an object.
The function takes the following 3 arguments:
Name | Description |
---|---|
object | the object to which the attribute is added |
name | the name of the attribute |
value | the 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.
Alternatively, you can use a list comprehension.
This is a three-step process:
range
object.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
We used a list comprehension to iterate over a range
object with a length of
5
.
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.
To append items to a list in a class:
__init__()
method.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']
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.
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.
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 tasks
variable is a class variable, so it is shared by all instances.
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.
You can use the list.extend()
method to append the items of an iterable to a
list.
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']
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.
You can learn more about the related topics by checking out the following tutorials: