Home > Mobile >  Cannot append value to list in Python?
Cannot append value to list in Python?

Time:10-06

I am creating a custom class mylist that inherits from list in python.

But I am unable to append values

class mylist(list):

    def __init__(self,max_length):
        super().__init__()
        self.max_length = max_length        

    def append(self, *args, **kwargs):
        """ Append object to the end of the list. """
        if len(self) > self.max_length:
            raise Exception

a = mylist(5)
a.append(5)
print(a)

# output
#[]

CodePudding user response:

You defined own append() so you replaced original append() and it doesn't add element to list.

You could use super() to run original append()

    def append(self, *args, **kwargs):
        """ Append object to the end of the list. """
        if len(self) > self.max_length:
            raise Exception

        if args:
            super().append(args[0])

I think you should use >= instead of > because you check it before adding item. You could use > if you would check it after adding item


BTW:

Because you use *args so you can use for-loop to append may values a.append(5, 6, 7). Original append() can't do this.

        for item in args:        
            super().append(item)

It may need to check if len(self) len(args) > self.max_length or it may need to check len(self) inside for-loop

You could also check if args has any value and raise error when you run a.append() without any value.


class MyList(list):  # PEP8: `CamelCaseNames` for classes

    def __init__(self, max_length):
        super().__init__()
        self.max_length = max_length        

    def append(self, *args, **kwargs):
        """ Append object to the end of the list. """
        #if len(self) >= self.max_length:
        #    raise Exception
        
        #if args:
        #    super().append(args[0])

        if not args: # use `TypeError` like in `list.append()`
            raise TypeError("descriptor 'append' of 'list' object needs an argument")

        for item in args:
            if len(self) >= self.max_length:
                 raise Exception
            super().append(item)

#list.append()  # raise `TypeError`
            
a = MyList(5)

try:
    a.append()  # raise `TypeError` like in `list.append()`
except Exception as ex:
    print('ex:', ex)

a.append(5)
print(a)      # [5]

a.append(6, 7, 8, 9)
print(a)      # [5, 6, 7, 8, 9]

a.append(10)  # raise ERROR

PEP 8 -- Style Guide for Python Code

CodePudding user response:

You mean this?

class mylist(list):

    def __init__(self,lists:list,max_length:int):
        super().__init__()
        self.lists = lists
        self.max_length = max_length
    def get_list(self):
        return self.lists
    def append(self, *args, **kwargs):
        if len(self.lists) > self.max_length:
            raise Exception
        else:
            self.lists.append(*args)

a = mylist([5,4,3,2])
a.append(54)
print(a.lists)
#OR
print(a.get_list())
  • Related