Python Create List of Objects

You can create a list of objects using the list comprehension statement [MyObject() for _ in range(n)] that repeats n times the creation of a new object using the MyObject() constructor. The result is a list of n new objects (not copies).

Here’s a minimal example:

class MyObject(object):
    pass


def return_objects(n):
    return [MyObject() for _ in range(n)]


print(return_objects(3))

You can see that all of them point to different objects in the memory in the following interactive memory visualization. Feel free to go back to step 1 and click through the execution step of the previous code snippet using the Next button:

Create List of Objects using Square Bracket Notation and append()

Everything in Python is an object, even functions and class definitions themselves. A list can hold any object whatsoever. So, technically, every list is a list of objects.

A more explicit way to create a list of objects is creating an initial list by adding comma-separated objects in the square bracket notation [1, 2, 3] and adding more objects one-by-one using list.append().

The following shows a wild assignment of different types of objects into the list using the square bracket notation:

>>> class MyClass: pass
>>> lst = [MyClass(), 'hello', 1, 3.14, MyClass, int, str, list, list()]
>>> lst
[<__main__.MyClass object at 0x0000019E353134F0>, 'hello', 1, 3.14, <class '__main__.MyClass'>, <class 'int'>, <class 'str'>, <class 'list'>, []]

Let’s add three elements using list.append():

>>> lst.append(1)
>>> lst.append(2)
>>> lst.append(3)
>>> lst
[<__main__.MyClass object at 0x0000019E353134F0>, 'hello', 1, 3.14, <class '__main__.MyClass'>, <class 'int'>, <class 'str'>, <class 'list'>, [], 1, 2, 3]

Going to the Next Level

An interesting tutorial for you may be the following on the Finxter blog (human recommendation engine):

🌍 Recommended Tutorial: How to Create a Python List?

Check it out, there’s lots of value there!

Also, if you want to improve your coding skills, I’d love to see you in my free email academy. We have cheat sheets too!