Initialize a list of objects in Python


I'm a looking to initialize an array/list of objects that are not empty -- the class constructor generates data. In C++ and Java I would do something like this:

Object lst = new Object[100];

I've dug around, but is there a Pythonic way to get this done?

This doesn't work like I thought it would (I get 100 references to the same object):

lst = [Object()]*100

But this seems to work in the way I want:

lst = [Object() for i in range(100)]

List comprehension seems (intellectually) like "a lot" of work for something that's so simple in Java.

lst = [Object() for i in range(100)]

Since an array is it's own first class object in python I think this is the only way to get what you're looking for. * does something crazy.

By : Paul Huff

I think the list comprehension is the simplest way, but, if you don't like it, it's obviously not the only way to obtain what you desire -- calling a given callable 100 times with no arguments to form the 100 items of a new list. For example, itertools can obviously do it:

You should note that Python's equvalent for Java code (creating array of 100 null references to Object):

Object arr = new Object[100];

or C code:

Object **arr = new Object*[100];


arr = [None]*100


arr = [Object() for _ in range(100)]

The second would be the same as Java's:

Object arr = new Object[100];
for (int i = 0; i 

This video can help you solving your question :)
By: admin