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.
To initialize a list in Python assign one with square brackets, initialize with the list() function, create an empty list with multiplication, or use a list comprehension.
We can create list of object in Python by appending class instances to list. By this, every index in the list can point to instance attributes and methods of the class and can access them. If you observe it closely, a list of objects behaves like an array of structures in C.
Using the list() function to initialize the list in Python. It is another way to create an empty list without values in Python as the list() function creates the list from the iterable object. An iterable may be a container, a sequence that supports iteration, or an iterator object.
As mentioned above, in Python, you can easily add and remove elements from a list, so in most cases, it is not necessary to initialize the list in advance. If you want to initialize a list of any number of elements where all elements are filled with any values, you can use the * operator as follows.
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With