57

How do I go about creating a list of objects (class instances) in Python?

Or is this a result of bad design? I need this cause I have different objects and I need to handle them at a later stage, so I would just keep on adding them to a list and call them later.

martineau
124k29 gold badges181 silver badges319 bronze badges
asked Jul 5, 2010 at 21:10
3
  • 2
    Do you mean a list of type objects ([type(x), ... ]) or instances of a class ([1, 2, 3])? Commented Jul 5, 2010 at 21:12
  • 4
    @Skurmedel: class instances. I mentioned it specifically in the question :) Commented Jul 6, 2010 at 5:07
  • @Alfred: hehe, I just find class instances a bit ambiguous, but I see what you mean now through the selected answer :P Commented Jul 6, 2010 at 11:29

8 Answers 8

100

Storing a list of object instances is very simple

class MyClass(object):
 def __init__(self, number):
 self.number = number
my_objects = []
for i in range(100):
 my_objects.append(MyClass(i))
# Print the number attribute of each instance
for obj in my_objects:
 print(obj.number)
answered Jul 5, 2010 at 21:24
Sign up to request clarification or add additional context in comments.

4 Comments

Where you pass "object" in the first line, is that an actual object or just a number signifying that object instance's number? If I were to write my_objects(1), I would call to the first object, but I don't think the 1 being passed in is an object. This might be entirely orthogonal to the educational purposes of the original response, but it would help me on a different, related topic I'm struggling with. Thanks.
T'was hoping there was a shiny special syntax for this :(
@Brad English, that indicates that MyClass inherits the properties of an object
The i in MyClass (i) refers to the number in the class's __init__ function.
27

You can create a list of objects in one line using a list comprehension.

class MyClass(object): pass
objs = [MyClass() for i in range(10)]
print(objs)
answered Feb 7, 2019 at 7:38

4 Comments

This is really clean syntax.
Slight detail: objs = [MyClass(i) for i in range(10)]
@Brainless, in this answer, the MyClass() initializer does not take an argument (in one of the other answers, it does...).
The usual python idiom is to use _ for loop variables that aren't referenced in the loop body (i.e. objs = [MyClass() for _ in range(10)])
5

The Python Tutorial discusses how to use lists.

Storing a list of classes is no different than storing any other objects.

def MyClass(object):
 pass
my_types = [str, int, float, MyClass]
answered Jul 5, 2010 at 21:13

Comments

4

In Python, the name of the class refers to the class instance. Consider:

class A: pass
class B: pass
class C: pass
lst = [A, B, C]
# instantiate second class
b_instance = lst[1]()
print b_instance
answered Jul 6, 2010 at 1:26

Comments

3

I have some hacky answers that are likely to be terrible... but I have very little experience at this point.

a way:

class myClass():
 myInstances = []
 def __init__(self, myStr01, myStr02):
 self.myStr01 = myStr01
 self.myStr02 = myStr02
 self.__class__.myInstances.append(self)
myObj01 = myClass("Foo", "Bar")
myObj02 = myClass("FooBar", "Baz")
for thisObj in myClass.myInstances:
 print(thisObj.myStr01)
 print(thisObj.myStr02)

A hack way to get this done:

import sys
class myClass():
 def __init__(self, myStr01, myStr02):
 self.myStr01 = myStr01
 self.myStr02 = myStr02
myObj01 = myClass("Foo", "Bar")
myObj02 = myClass("FooBar", "Baz")
myInstances = []
myLocals = str(locals()).split("'")
thisStep = 0
for thisLocalsLine in myLocals:
 thisStep += 1
 if "myClass object at" in thisLocalsLine:
 print(thisLocalsLine)
 print(myLocals[(thisStep - 2)])
 #myInstances.append(myLocals[(thisStep - 2)])
 print(myInstances)
 myInstances.append(getattr(sys.modules[__name__], myLocals[(thisStep - 2)]))
for thisObj in myInstances:
 print(thisObj.myStr01)
 print(thisObj.myStr02)

Another more 'clever' hack:

import sys
class myClass():
 def __init__(self, myStr01, myStr02):
 self.myStr01 = myStr01
 self.myStr02 = myStr02
myInstances = []
myClasses = {
 "myObj01": ["Foo", "Bar"],
 "myObj02": ["FooBar", "Baz"]
 }
for thisClass in myClasses.keys():
 exec("%s = myClass('%s', '%s')" % (thisClass, myClasses[thisClass][0], myClasses[thisClass][1]))
 myInstances.append(getattr(sys.modules[__name__], thisClass))
for thisObj in myInstances:
 print(thisObj.myStr01)
 print(thisObj.myStr02)
answered Jan 15, 2018 at 16:59

Comments

0

if my_list is the list that you want to store your objects in it and my_object is your object wanted to be stored, use this structure:

my_list.append(my_object)
answered Mar 24, 2016 at 8:59

Comments

0

We have class for students and we want make list of students that each item of list is kind of student

class student :
 def __init__(self,name,major):
 self.name=name
 self.major=major
students = []
count=int(input("enter number of students :"))
#Quantify
for i in range (0,count):
 n=input("please enter name :")
 m=input("please enter major :")
 students.append(student(n,m))
#access
for i in students:
 print (i.name,i.major)
pipe
74010 silver badges29 bronze badges
answered Jun 26, 2022 at 10:55

1 Comment

As it’s currently written, your answer is unclear. Please edit to add additional details that will help others understand how this addresses the question asked. You can find more information on how to write good answers in the help center.
-3

I think what you're of doing here is using a structure containing your class instances. I don't know the syntax for naming structures in python, but in perl I could create a structure obj.id[x] where x is an incremented integer. Then, I could just refer back to the specific class instance I needed by referencing the struct numerically. Is this anything in the direction of what you're trying to do?

answered Jul 6, 2010 at 0:45

Comments

Your Answer

Draft saved
Draft discarded

Sign up or log in

Sign up using Google
Sign up using Email and Password

Post as a guest

Required, but never shown

Post as a guest

Required, but never shown

By clicking "Post Your Answer", you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.