how to create an list of a specific type but empty

Question:

How to create a list of a specific type of object but empty? Is it possible? I want to create an array of objects (the type is called Ghosts) which later will contain different types that inherit from that one class called Ghosts. It’s all very simple in C++ but i’m not sure how to do that in python. I tried something like this:

self.arrayOfGhosts = [[Ghost() for x in xrange(100)] for x in xrange(100)]

but it’s already initialised by objects, and I don’t need it, is there a way to initialise it by 0 but have an list of type Ghost?

As you see I’m very new to python. Any help will be highly appreciated.

Asked By: user3623738

||

Answers:

Those are lists, not arrays. Python is a duck-typed language. Lists are heterogenously-typed anyway. For example. your list can contain an int, followed by str, followed by list, or whatever suits your fancy. You cannot restrict the type with stock classes, and that’s against the philosophy of the language.

Just create an empty list, and add later.

self.arrayOfGhosts = []

Two-dimensional lists are simple. Just nest lists.

l = [[1, 2, 3], [4, 5, 6]]
l[0]  # [1, 2, 3]
l[1][2]  # 6

If you really want placeholders, just do something like the following.

[[None] * 100 for i in range(100)]

Python doesn’t have arrays, unless you mean array.array, which is for C-ish types anyways. Arrays are the wrong level of abstraction in Python most of the time.

P.S. If you’re using xrange, then you must be using Python 2. Unless you need very specific libraries, please stop, and use Python 3. See why.

P.P.S. You initialize with NULL, not 0 in C++. Never use 0 to mean NULL.

P.P.P.S. See PEP 8, the canonical Python style guide.

Answered By: pilona

Python is a dynamic language so there is no concept of array of type.
You create an empty generic list with:

self.arrayOfGhosts = []

You don’t care about the capacity of the list as it’s dynamically allocated as well.
It’s up to you to fill it with as many Ghost instances as you wish with:

self.arrayOfGhosts.append(Ghost())

The above is really enough, however:
If you really want to enforce this list to accept only Ghost and inheriting classes instances, you can create a custom list type like this:

class GhostList(list):

    def __init__(self, iterable=None):
        """Override initializer which can accept iterable"""
        super(GhostList, self).__init__()
        if iterable:
            for item in iterable:
                self.append(item)

    def append(self, item):
        if isinstance(item, Ghost):
            super(GhostList, self).append(item)
        else:
            raise ValueError('Ghosts allowed only')

    def insert(self, index, item):
        if isinstance(item, Ghost):
            super(GhostList, self).insert(index, item)
        else:
            raise ValueError('Ghosts allowed only')

    def __add__(self, item):
        if isinstance(item, Ghost):
            super(GhostList, self).__add__(item)
        else:
            raise ValueError('Ghosts allowed only')

    def __iadd__(self, item):
        if isinstance(item, Ghost):
            super(GhostList, self).__iadd__(item)
        else:
            raise ValueError('Ghosts allowed only')

Then for two-dimensional list you use this class like:

self.arrayOfGhosts = []
self.arrayOfGhosts.append(GhostList())
self.arrayOfGhosts[0].append(Ghost())
Answered By: ElmoVanKielmo

Lists in Python can grow as needed, they are not fixed in length like you might be used to in C or C++.

Therefore, there is no need to “initialize” a list in Python. Just create it when you need it, and then add to it as you like.

You absolutely don’t need a “zeroed list” of your Ghost objects, simply do this:

scary_farm = []  # This is an empty list.
ghosts = []

# .. much later down in your code

mean_ghost = Ghost(scary_level=10, voice='Booooo!')
ghosts.append(mean_ghost)

casper = Ghost(scary_level=-1, voice="I'm the friendly ghost. Hee hee!")
ghosts.append(casper)

# ... later on
scary_farm.append(ghosts) # Now you have your 2-D list

for item in scary_farm:
    for ghost in item:
        print('{0.voice}'.format(ghost))

Note you also don’t need a list of indexes when stepping through a list or any collection in Python. In C/C++ you might be used to:

for(i = 0; i < 10; i++)
{ 
    cout << scary_farm[i] << endl;
}

But this is not required in Python as collection types can be iterated over directly.

Answered By: Burhan Khalid

Since Python 3.5 you are able to do this:
https://docs.python.org/3/library/typing.html

self.arrayOfGhosts: list[Ghost] = []

You also can import List and use the following code:

from typing import List

self.arrayOfGhosts: List[Ghost] = []
Answered By: Code Pope
Categories: questions Tags: ,
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.