0

I'm trying to design a function in Python which instantiates a number of objects based on a user input. I've derived one which works, and it looks as follows

class Node(): ...

def initialise():
    binary_tree=[]
    opt=int(input("Enter the number of nodes you want\n"))
    for i in range(opt):
        a=Node()
        binary_tree.append(a)

although I'm not sure that this is the ideal way to do this.

Is there a better way of programming a function such as the one I've described, or is the above method sufficient for efficiency and clarity purposes?

Any responses are appreciated, thank you in advance.

  • 1
    You don't need to assign `Node` to `a`. Just directly do `binary_tree.append(Node())` – Chris Feb 27 '19 at 08:13
  • Possible duplicate of [Create an empty list in python with certain size](https://stackoverflow.com/questions/10712002/create-an-empty-list-in-python-with-certain-size) – D Malan Feb 27 '19 at 08:31

1 Answers1

0

Your code seems to work ok.

There are other options to format it; for example, you could use list comprehension, which might be slightly faster than using .append() and also uses slightly less code:

def initialise():
    opt = int(input("Enter the number of nodes you want\n"))

    return [
        Node()
        for _ in range(opt)]

Careful: this (as well as your version) code might raise a ValueError if the uses enters a string that cannot be converted to int.

Ralf
  • 16,086
  • 4
  • 44
  • 68