Open In App

How to create a list of object in Python class

Last Updated : 15 Jan, 2023
Improve
Improve
Like Article
Like
Save
Share
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



Previous Article
Next Article

Similar Reads

Object Oriented Programming in Python | Set 2 (Data Hiding and Object Printing)
Prerequisite: Object-Oriented Programming in Python | Set 1 (Class, Object and Members) Data hiding In Python, we use double underscore (Or __) before the attributes name and those attributes will not be directly visible outside. Python Code class MyClass: # Hidden member of MyClass __hiddenVariable = 0 # A member method that changes # __hiddenVari
3 min read
Create Derived Class from Base Class Universally in Python
In object-oriented programming, the concept of inheritance allows us to create a new class, known as the derived class, based on an existing class, referred to as the base class. This facilitates code reusability and structuring. Python provides a versatile way to create derived classes from base classes universally, allowing for flexibility and sc
3 min read
Python | Create a stopwatch using clock object in kivy using .kv file
Kivy is a platform-independent GUI tool in Python. As it can be run on Android, IOS, Linux and Windows, etc. It is basically used to develop the Android application, but it does not mean that it can not be used on Desktop applications. Kivy Tutorial - Learn Kivy with Examples. Clock Object: The Clock object allows you to schedule a function call in
6 min read
Python | Create a stopwatch Using Clock Object in kivy
Kivy is a platform-independent GUI tool in Python. As it can be run on Android, IOS, Linux and Windows, etc. It is basically used to develop the Android application, but it does not mean that it can not be used on Desktop applications.In this, we are going to see how can we create a stopwatch using a label. In the code, we will be creating just a c
4 min read
Create and display a one-dimensional array-like object using Pandas in Python
Series() is a function present in the Pandas library that creates a one-dimensional array and can hold any type of objects or data in it. In this article, let us learn the syntax, create and display one-dimensional array-like object containing an array of data using Pandas library. pandas.Series() Syntax : pandas.Series(parameters) Parameters : dat
2 min read
Convert class object to JSON in Python
Conversion of the class object to JSON is done using json package in Python. json.dumps() converts Python object into a json string. Every Python object has an attribute which is denoted by __dict__ and this stores the object's attributes. Object is first converted into dictionary format using __dict__ attribute.This newly created dictionary is pas
2 min read
Python program to create a list of tuples from given list having number and its cube in each tuple
Given a list of numbers of list, write a Python program to create a list of tuples having first element as the number and second element as the cube of the number. Example: Input: list = [1, 2, 3] Output: [(1, 1), (2, 8), (3, 27)] Input: list = [9, 5, 6] Output: [(9, 729), (5, 125), (6, 216)] Method #1 : Using pow() function.We can use list compreh
5 min read
Python - Create nested list containing values as the count of list items
Given a list, the task is to write a Python program to create a nested list where the values are the count of list items. Examples: Input: [1, 2, 3] Output: [[1], [2, 2], [3, 3, 3]] Input: [4, 5] Output: [[1, 1, 1, 1], [2, 2, 2, 2, 2]] Method 1: Using nested list comprehension The list will contain the count of the list items for each element e in
2 min read
Create List of Substrings from List of Strings in Python
In Python, when we work with lists of words or phrases, we often need to break them into smaller pieces, called substrings. A substring is a contiguous sequence of characters within a string. Creating a new list of substrings from a list of strings can be a common task in various applications. In this article, we will create a new list of substring
3 min read
Python | Check if a given object is list or not
Given an object, the task is to check whether the object is list or not. Method #1: Using isinstance C/C++ Code # Python code to demonstrate # check whether the object # is a list or not # initialisation list ini_list1 = [1, 2, 3, 4, 5] ini_list2 = '12345' # code to check whether # object is a list or not if isinstance(ini_list1, list): print(&
2 min read
Practice Tags :