How to create a list of object in Python class
Last Updated :
15 Jan, 2023
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
class geeks:
def __init__( self , name, roll):
self .name = name
self .roll = roll
list = []
list .append(geeks( 'Akash' , 2 ))
list .append(geeks( 'Deependra' , 40 ))
list .append(geeks( 'Reaper' , 44 ))
list .append(geeks( 'veer' , 67 ))
for obj in list :
print (obj.name, obj.roll, sep = ' ' )
print ("")
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
class geeks:
def __init__( self , x, y):
self .x = x
self .y = y
def Sum ( self ):
print ( self .x + self .y)
list = []
list .append(geeks( 2 , 3 ))
list .append(geeks( 12 , 13 ))
list .append(geeks( 22 , 33 ))
for obj in list :
obj. Sum ()
|
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
class geeks:
def __init__( self , name, roll):
self .name = name
self .roll = roll
list = []
list + = [geeks(name, roll) for name, roll in [( 'Akash' , 2 ), ( 'Deependra' , 40 ), ( 'Reaper' , 44 ), ( 'veer' , 67 )]]
for obj in list :
print (obj.name, obj.roll, sep = ' ' )
|
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
Share your thoughts in the comments
Please Login to comment...