Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

how to create an list of a specific type but empty

Tags:

python

object

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.

like image 592
user3623738 Avatar asked Jun 11 '14 10:06

user3623738


People also ask

How do I create an empty string list?

You can create a list of n empty strings using the list concatenation (multiplication) operator on a list with one empty string using the expression [''] * n . This replicates the same identical empty string object to which all list elements refer.

How can we create a empty list in Python?

An empty list in Python can be created in two ways, either by using square brackets [] or by using the list() constructor.


2 Answers

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())
like image 170
ElmoVanKielmo Avatar answered Nov 12 '22 14:11

ElmoVanKielmo


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.

like image 2
pilona Avatar answered Nov 12 '22 15:11

pilona