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 Lazyroar: def __init__( self , name, roll): self .name = name self .roll = roll # creating list list = [] # appending instances to list list .append(Lazyroar( 'Akash' , 2 )) list .append(Lazyroar( 'Deependra' , 40 )) list .append(Lazyroar( 'Reaper' , 44 )) list .append(Lazyroar( '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) |
Akash 2 Deependra 40 Reaper 44 veer 67 Akash Deependra Reaper veer
Example #2:
Python3
# Python3 code here for creating class class Lazyroar: 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(Lazyroar( 2 , 3 )) list .append(Lazyroar( 12 , 13 )) list .append(Lazyroar( 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. |
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 Lazyroar: def __init__( self , name, roll): self .name = name self .roll = roll # creating list list = [] # using list comprehension to append instances to list list + = [Lazyroar(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 |
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 Lazyroar class and appending them to the list