How to create a list of object in Python class

This illustration joins items, classes, and records. You will figure out how to make, access, update records and furthermore how to plan Python code with classes and arrangements of items.
Records

Python offers a scope of compound datatypes frequently alluded to as successions. List is one of the most often utilized and it is an extremely flexible datatype, which can be composed as a rundown of comma-isolated qualities (things) between square sections. Significant thing about a rundown is that things in a rundown need not be of a similar kind.

How to create a list?

In Python programming, a list is created by placing all the items (elements) inside a square bracket, separated by commas. For example:

  1. mylist = [‘a’, ‘c’, ‘d’, 3, 4]
  2. print(mylist)

Access items in a list

You access the list items by referring to the index number. Index starts from 0. So, a list having 10 elements will have index from 0 to 9. Python, also, allows negative indexing for its sequences. The index of -1 refers to the last item, -2 to the second last item and so on. For example:

  1. mylist = [1, 1, 2, 3, 5, 8, 13, 21, 34]
  2. print(‘The 5-th element of the list is:’, mylist[4])
  3. #The 5-th element of the list is: 5
  4. print(‘The last element of the list is:’, mylist[-1])
  5. #The last element of the list is: 34
  6. print(‘Elements: 3rd to 5th:’, mylist[2:5])
  7. #Elements: 3rd to 5th: [2, 3, 5]
  8. print(‘Elements: 4th to end:’, mylist[3:])
  9. #Elements: 4th to end: [3, 5, 8, 13, 21, 34]

Update a list

List are mutable, meaning, their elements can be changed.

  • To change the value of a specific item, refer to the index number.
  • To add to elements in a list use the append() method.
  • To delete one or more items from a list use the keyword del or the remove method.

For example:

  1. mylist = [1, 1, 2, 3, 5, 5, 13, 21, 34]
  2. mylist[5] = 8
  3. print(‘List after changing the value of 6th element:’, mylist)
  4. # List after changing the value of 6th element: [1, 1, 2, 3, 5, 8, 13, 21, 34]
  5. mylist.append(55)
  6. print(‘List after appending 55:’, mylist)
  7. # List after appending 55: [1, 1, 2, 3, 5, 8, 13, 21, 34, 55]
  8. mylist.remove(55)
  9. print(‘List after removing 55:’, mylist)
  10. # List after removing 55: [1, 1, 2, 3, 5, 8, 13, 21, 34]
  11. del mylist[-1]
  12. print(‘List after deleting the last element:’, mylist)
  13. # List after deleting the last element: [1, 1, 2, 3, 5, 8, 13, 21]

Iterating Through a List

Using a for loop we can iterate though each item in a list. For example:

  1. mylist = [1, 1, 2, 3, 5, 8, 13, 21, 34]
  2. for number in mylist:
  3.    print(‘number: ‘, number)

Built-in Functions with List

Built-in functions like len(), max(), min(), list(), sorted() etc. are commonly used with list to perform different tasks.

  • all(): Return True if all elements of the list are true (or if the list is empty).
  • any(): Return True if any element of the list is true. If the list is empty, return False.
  • enumerate(): Return an enumerate object. It contains the index and value of all the items of list as a tuple.
  • len(): Return the length of a list (the number of items in a list).
  • list(): Convert an iterable (tuple, string, set, dictionary) to a list.
  • max(): Return the largest item in the list.
  • min(): Return the smallest item in the list
  • sorted(): Return a new sorted list (does not sort the list itself).
  • sum(): Return the sum of all elements in the list.

For example:

  1. mylist = [1, 7, 2, 11, 5, 21, 13, 5, 4]
  2. print(‘Sorted list:’, sorted(mylist))
  3. # Sorted list: [1, 2, 4, 5, 5, 7, 11, 13, 21]
  4. print(‘Sum of elements:’, sum(mylist))
  5. # Sum of elements: 69
  6. print(‘Max element:’, max(mylist))
  7. # Max element: 21
  8. print(‘Min element:’, min(mylist))
  9. # Min element: 1
  10. print(‘Length of list:’, len(mylist))
  11. # Length of list: 9

We can make rundown of item in Python by adding class examples to list. By this, each record in the rundown can highlight occasion credits and strategies for the class and can get to them. In the event that you notice it intently, a rundown of articles acts like a variety of constructions in C. How about we attempt to comprehend it better with the assistance of models.

Model #1:

Consideration nerd! Fortify your establishments with the Python Programming Foundation Course and gain proficiency with the nuts and bolts.

Regardless, your meeting arrangements Enhance your Data Structures ideas with the Python DS Course. What’s more in any case your Machine Learning Journey, join the Machine Learning – Basic Level Course

# 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.
Output:
Akash 2
Deependra 40
Reaper 44

Example #2:

# Python3 code here for creating class
class geeks: 
    def __init__(self, x, y): 
        self.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

How to create a list of objects in Python

Python objects defined by a user constructed class can be members of a list like any other data type. A list of objects is a list where each element is a different instance of some class

USE list TO CREATE A LIST OF OBJECTS

Call the class constructor for every element, then create a list containing each object instance.

class number_object(object):
    def __init__(self, number):
        self.number = number

object_0 =  number_object(0)
object_1 =  number_object(1)
object_2 =  number_object(2)


object_list = [object_0, object_1, object_2]

for obj in object_list:
     print(obj.number)
OUTPUT
0
1
2

Also Read: Reverse a string in Java

Leave a Reply

Your email address will not be published.