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
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
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
>>> 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!
While working as a researcher in distributed systems, Dr. Christian Mayer found his love for teaching computer science students.
To help students reach higher levels of Python success, he founded the programming education website Finxter.com that has taught exponential skills to millions of coders worldwide. He’s the author of the best-selling programming books Python One-Liners (NoStarch 2020), The Art of Clean Code (NoStarch 2022), and The Book of Dash (NoStarch 2022). Chris also coauthored the Coffee Break Python series of self-published books. He’s a computer science enthusiast, freelancer, and owner of one of the top 10 largest Python blogs worldwide.
His passions are writing, reading, and coding. But his greatest passion is to serve aspiring coders through Finxter and help them to boost their skills. You can join his free email academy here.