Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Initialize a list of objects in Python

Tags:

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.

like image 969
bradreaves Avatar asked Nov 27 '09 06:11

bradreaves


People also ask

How do you initialize a list object in Python?

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.

Can you make a list of objects in Python?

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.

What does it mean to initialize a list in Python?

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.

Do you need to initialize a list in Python?

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.


1 Answers

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
like image 197
Greg Hewgill Avatar answered Sep 19 '22 18:09

Greg Hewgill