0

is there a data structure in python that is equivalent to array in cpp? one that some elements are initialized and some are not? for example, in python list: [1,2,3], elements have to be sequentially filled in cpp array can be a[0] == 0, a1 -- arbitrary, uninitialized, a[2] == 2

is there an cpp-array equivalent structure in python? ps, python array doesn't seem to be equivalent, all elements have to be filled sequentially too

enter image description here

lokusking
  • 7,396
  • 13
  • 38
  • 57
Ashley Liu
  • 31
  • 1
  • 3

2 Answers2

1

Perhaps this answer here on StackOverflow may be what you are looking for?

How to create a fix size list in python?

Guerry
  • 739
  • 4
  • 10
0

You can probably put together some kind of wrapper using a dictionary:

class CppArray:
    def __init__(self, value):
        if value == None:
            self.data = {}
            self.length = 0
        else:
            self.data = { 0: value }
            self.length = 1

    def insert(self, index, value):
        while index in self.data:
            tmp = self.data[index]
            self.data[index] = value
            value = tmp
            index = index + 1
        self.data[index] = value
        if index >= self.length:
            self.length = index + 1

    def __getitem__(self, index):
        if (index < 0 or index >= self.length):
            # must create IndexException
            raise IndexException("Index out of range")
        if index in self.data:
            return self.data[index]
        else:
            return None

x = CppArray("i")
x.insert(0,10)
x.insert(200,30)
x[1]

Obviously this quick sketch is missing many details which would make the class more useful.

For other ideas on special methods you could use, check:

https://docs.python.org/3/reference/datamodel.html