How to create a list of object in Python class
We can create list of object in Python by appending class instances to list. By this, every index in the list can point to instance attribute and methods of class and can access them. If you observe it closely, list of objects behaves like an array of structures in C. Let’s try to understand it better with help of examples.
Example #1:
# 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) ) for obj in list: print( obj.name, obj.roll, sep =' ' ) # We can also access instances attributes # as list[0].name, list[0].roll and so on. |
chevron_right
filter_none
Output:
Akash 2 Deependra 40 Reaper 44
Example #2:
# 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. |
chevron_right
filter_none
Output:
5 25 55
Recommended Posts:
- Object Oriented Programming in Python | Set 1 (Class, Object and Members)
- Python | Create a stopwatch Using Clock Object in kivy
- Python program to create a list of tuples from given list having number and its cube in each tuple
- Python | Create a stopwatch using clock object in kivy using .kv file
- Python Tkinter | Create different shapes using Canvas class
- Python Tkinter | Create different type of lines using Canvas class
- Python program to create Bankaccount class with deposit, withdraw function
- Python | Ways to create triplets from given list
- Python | Create a dictionary using list with none values
- Python | Create list of numbers with given range
- Python program to create a list centered on zero
- Python | Check if a given object is list or not
- Object Oriented Programming in Python | Set 2 (Data Hiding and Object Printing)
- Create a list from rows in Pandas dataframe
- Create a Pandas DataFrame from List of Dicts
If you like GeeksforGeeks and would like to contribute, you can also write an article using contribute.geeksforgeeks.org or mail your article to contribute@geeksforgeeks.org. See your article appearing on the GeeksforGeeks main page and help other Geeks.
Please Improve this article if you find anything incorrect by clicking on the "Improve Article" button below.



