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:
There isn't a way to implicitly call an Object()
constructor for each element of an array like there is in C++ (recall that in Java, each element of a new array is initialised to null
for reference types).
I would say that your list comprehension method is the most Pythonic:
lst = [Object() for i in range(100)]
If you don't want to step on the lexical variable i
, then a convention in Python is to use _
for a dummy variable whose value doesn't matter:
lst = [Object() for _ in range(100)]
For an equivalent of the similar construct in Java, you can of course use *
:
lst = [None] * 100