Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Create a list of default objects of a class in Python?

Tags:

python

I have define a class in Python

class node(object):
    def __init__(self, children = []):
        self.children = children

I would like to create a list or array of default objects of class node. For example, something like in C++

node * nodes = node[100];

then nodes will point to an array of 100 default objects of class node.

How is it done similarly in Python? Thanks.

like image 964
Tim Avatar asked Dec 06 '22 00:12

Tim


2 Answers

Using a list comprehension:

nodes = [node() for _ in range(100)]
like image 104
Roger Fan Avatar answered Dec 10 '22 11:12

Roger Fan


You can use a list comprehension:

nodes = [node() for _ in range(100)]

Python doesn't have a concept of "arrays" per se, but it has lists which are a higher-level structure. Lists can be indexed just like C arrays, and support many more complex operations.

like image 39
arshajii Avatar answered Dec 10 '22 10:12

arshajii