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

1
  • By what way it is not "equivalent"? Just because you cannot leave garbage in certain element of list? Commented Oct 18, 2016 at 5:19

2 Answers 2

1

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

How to create a fix size list in python?

Sign up to request clarification or add additional context in comments.

Comments

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.