Open In App

How to create a list of object in Python class

Improve
Improve
Improve
Like Article
Like
Save Article
Save
Share
Report issue
Report

We can create a list of objects in Python by appending class instances to the list. By this, every index in the list can point to instance attributes and methods of the class and can access them. If you observe it closely, a list of objects behaves like an array of structures in C. Let’s try to understand it better with the help of examples.

 Example #1: 

Python3




# Python3 code here creating class
class geeks:
    def __init__(self, name, roll):
        self.name = name
        self.roll = roll
 
# creating list
list = []
 
# appending instances to list
list.append(geeks('Akash', 2))
list.append(geeks('Deependra', 40))
list.append(geeks('Reaper', 44))
list.append(geeks('veer', 67))
 
# Accessing object value using a for loop
for obj in list:
    print(obj.name, obj.roll, sep=' ')
 
print("")
# Accessing individual elements
print(list[0].name)
print(list[1].name)
print(list[2].name)
print(list[3].name)


Output

Akash 2
Deependra 40
Reaper 44
veer 67

Akash
Deependra
Reaper
veer

  Example #2: 

Python3




# Python3 code here for creating class
class geeks:
    def __init__(self, x, y):
        self.x = x
        self.y = y
 
    def Sum(self):
        print(self.x + self.y)
 
 
# creating list
list = []
 
# appending instances to list
list.append(geeks(2, 3))
list.append(geeks(12, 13))
list.append(geeks(22, 33))
 
for obj in list:
    # calling method
    obj.Sum()
 
# We can also access instances method
# as list[0].Sum() , list[1].Sum() and so on.


Output

5
25
55

Method #3: Using a list comprehension

This approach creates a list of objects by iterating over a range of numbers and creating a new object for each iteration. The objects are then appended to a list using a list comprehension.

Python3




# Python3 code here creating class
class geeks:
    def __init__(self, name, roll):
        self.name = name
        self.roll = roll
  
# creating list
list = []
  
# using list comprehension to append instances to list
list += [geeks(name, roll) for name, roll in [('Akash', 2), ('Deependra', 40), ('Reaper', 44), ('veer', 67)]]
  
# Accessing object value using a for loop
for obj in list:
    print(obj.name, obj.roll, sep=' ')
#This code is contributed by Edula Vinay Kumar Reddy


Output

Akash 2
Deependra 40
Reaper 44
veer 67

Time complexity: O(n) where n is the number of instances being appended to the list
Auxiliary Space: O(n) as we are creating n instances of the geeks class and appending them to the list



Last Updated : 15 Jan, 2023
Like Article
Save Article
Previous
Next
Share your thoughts in the comments
Similar Reads