0

I am trying to create Array which will get bunch of customization. However, I was stuck while adding custom insert method which just adds new value to the end of array. This is my code:

class Array():
    type_object = [int, str, float]
    count = 0

    def __init__(self, typecode):
        self.array = []
        if typecode in self.type_object:
            self.typecode = typecode

    def __str__(self):
        return f"{self.array}"

    def __iter__(self):
        return iter(self.array)   
    
    def insert(self, value):
        try:
            if type(value) != self.typecode:
                raise ValueError("Invalid type")
        except ValueError as ex:
            print(ex)
        self.array[self.count] = value
        self.count += 1

a = Array(int)
a.insert(1)

"Classic" Error:

List index out of range

I want to avoid .append() method in order to make it "super-customized" so to say. How to allocate a fixed size of memory ahead of time? I have seen "[None] * n" approach but the problem is when you print it out it gives bunch of None))

Any recomendation appreciated.

2 Answers2

0

self.array[self.count] = value can't put values at indices that don't exist.

self.array starts out empty, so the index 0 doesn't exist yet. You can use self.array.append(value) to append a new element.

ForceBru
  • 43,482
  • 10
  • 63
  • 98
  • How to allocate fixed size of memory ahead of time. I have seen "[None] * n" approach but the problem is when you print it out it gives bunch of None)) –  Mar 04 '21 at 18:34
  • I want to avoid .append() method in order to make it "super-customized" so to say. Is the there any way to implement it internally, for instance? –  Mar 04 '21 at 18:44
  • @DavudMursalov, appending to lists is done with `.append`, which is a built-in method - you can't go any more "internal" than that, unless you modify Python's source code. So, you can't have a "super customized" list because you'll have to use some built-in data structure to store the actual data. BTW, if you want to be able to insert data into an arbitrary index, you could use a dictionary: `{0: "el 0", 5: "index 5!", 7: "index 7"}`. – ForceBru Mar 04 '21 at 20:48
0

You should switch the insert function to append the array like so:

def insert(self, value):
    try:
        if type(value) != self.typecode:
            raise ValueError("Invalid type")
    except ValueError as ex:
        print(ex)
    self.array.append(value)
    self.count += 1

When you create self.array you allocate no memory for it as its an empty list. Thus when trying to set the 0th element you get an exception.

Juip
  • 171
  • 1
  • 6