Python create object list

Python create object list

Last updated: Feb 22, 2023
Reading time · 5 min

banner

# Table of Contents

# 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.
Copied!
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.

Copied!
print(list(range(5))) # 👉️ [0, 1, 2, 3, 4] print(list(range(1, 6))) # 👉️ [1, 2, 3, 4, 5]

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.

Copied!
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.

Copied!
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.

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.

Читайте также:  Python время минуты секунды

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.
Copied!
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 .

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.
Copied!
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.

Copied!
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.

Copied!
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.

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

Читайте также:  Class footer html это

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.

Copied!
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.

# 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.

Источник

4 different ways in Python to create a list of objects

Python list can hold a list of class objects. We can create one empty list and append multiple class objects to this list. Each list element will be an object, and we can access any member of that object like method, variables, etc. Note that you can append different class objects to the same list.

In this post, I will show you how to create one list of objects in Python and also how to append items to a list of objects.

How to add items to a list:

We have different methods to add items to a list.

The append method takes one item as its parameter and adds it to the end of the list. For example,

= [] l.append(1) l.append(2) l.append(3) print(l)

In this example, we created an empty list l and appended three numbers to the list. It will add these numbers to the end of the list l .

The insert method inserts an item into a list at any given position. The syntax of the insert method is:

Let’s take a look at the following example:

= [1, 2, 3, 4, 5] l.insert(1, -1) print(l)

It will insert -1 at index position 1 of the list l . It will shift the other elements to the right. The above example will print [1, -1, 2, 3, 4, 5] .

The extend method can add any iterable to a list. It takes the other iterable as its parameter and appends it to the original list.

= [1, 2, 3, 4, 5] l1 = [6, 7, 8] l.extend(l1) print(l)

It will print [1, 2, 3, 4, 5, 6, 7, 8] .

Example 1: How to create a list of objects with the same class instance:

Let’s take a look at the following program:

class Student: def __init__(self, name, age): self.name = name self.age = age studentList = [] studentList.append(Student("Alex", 20)) studentList.append(Student("Bob", 21)) studentList.append(Student("Ira", 15)) for student in studentList: print("Name : <>, Age : <>".format(student.name, student.age))

In this example, we are appending objects to a list. The Student is a class with two properties name and age . The constructor of the Student class takes the name and age properties as its parameters and initializes one Student object.

Читайте также:  Java search byte in byte array

First of all, we are initializing one empty list studentList and appending three different Student objects to this list. We are using the append method to append the items to the list.

The for loop is used to print the properties of the list objects.

It will print the below output :

: Alex, Age : 20 Name : Bob, Age : 21 Name : Ira, Age : 15

Python list objects

Example 2: list of objects with different class instances:

In the above example, we appended different objects of the same class to a list. We can also append objects of different classes to a list.

class Student: def __init__(self, name, age): self.name = name self.age = age class Subject: def __init__(self, name): self.subjectName = name data = [] data.append(Student("Alex", 20)) data.append(Subject("Subject-A")) data.append(Student("Bob", 21)) data.append(Subject("Subject-B")) data.append(Student("Ira", 15)) for item in data: if(isinstance(item, Student)): print('Name : <>, Age : <>'.format(item.name, item.age)) else: print('Subject : <>'.format(item.subjectName))

In this example, we have created two different classes Student and Subject . But we are appending objects of both of these classes to the same list data . The for loop is checking the type of the object before printing out its content.

It will produce the below output :

: Alex, Age : 20 Subject : Subject-A Name : Bob, Age : 21 Subject : Subject-B Name : Ira, Age : 15

Method 3: Create a list of objects with the extend method:

We can pass one list of objects to the extend function to append the items to another list. We can use the extend function with an empty list to create one list of objects.

class Student: def __init__(self, name, age): self.name = name self.age = age l = [] data = [Student("Alex", 20), Student("Bob", 21), Student("Ira", 15)] l.extend(data) for item in l: print("Name : <>, Age : <>".format(item.name, item.age))

It will append the items of the list data to the list l . The for loop will print the name and age of the list items.

: Alex, Age : 20 Name : Bob, Age : 21 Name : Ira, Age : 15

Method 4: Create a list of objects with the insert method:

The insert method can also be used to insert multiple items into an empty list. For example,

class Student: def __init__(self, name, age): self.name = name self.age = age l = [] l.insert(0, Student("Alex", 20)) l.insert(1, Student("Bob", 21)) l.insert(2, Student("Ira", 15)) for item in l: print("Name : <>, Age : <>".format(item.name, item.age))

The insert method is inserting the Student objects to the list l . If you run this program, it will print the below output:

: Alex, Age : 20 Name : Bob, Age : 21 Name : Ira, Age : 15

Источник

Оцените статью