Skip to content
Advertisement

Custom list class slicing functionality

I want to implement my own type of list called Stack. I also want to add slicing functionality with the __getitem__ method like so:

class Stack():
    def __init__(self):
        self.items = []

    def __getitem__(self, slc):
        return self.items[slc]

    def append(self, item):
        self.items.append(item)

Now if I create a Stack instance and append some elements to it I get the Stack type:

st = Stack()
st.append('hi')
st.append('bye')
st.append('hello')
print(type(st)) # Stack type

but if I slice my Stack, it becomes a list again:

st_sliced = st[1:2]
print(type(st_sliced)) # List type

how can I make st_sliced to stay Stack type after slicing?

Advertisement

Answer

return self.items[slc] return a list – this is why the type is not a Stack anymore.

The code below keep the type as Stack.

class Stack:
    def __init__(self, items=None):
        if items is None:
            items = []
        self.items = items

    def __getitem__(self, slc):
        return Stack(self.items[slc])

    def append(self, item):
        self.items.append(item)


st = Stack()
st.append('hi')
st.append('bye')
st.append('hello')
print(type(st))
st_sliced = st[1:2]
print(type(st_sliced))
User contributions licensed under: CC BY-SA
3 People found this is helpful
Advertisement