0

In python you have built-in functions that operate on lists such as list.remove() and list.pop().

Can you make your own custom functions that do this? I want to be able to do this:

def removeAll(self,value):
  while value in self:
    self.remove(value)

list = ["1","2","3","3","4","3","5"]
list.removeAll("3")
print(list)
#Outputs '["1","2","4","5"]

Just an example.

NerdKnight66
  • 11
  • 1
  • 2
  • As a general answer, [this might help](https://stackoverflow.com/questions/4698493/can-i-add-custom-methods-attributes-to-built-in-python-types) – sj95126 Jul 29 '21 at 05:08
  • You want to extend `List` class or it will be single function that takes `list` as input and new list as output ? – Sociopath Jul 29 '21 at 05:08

2 Answers2

0

You can't modify the built-in types, but you can certainly derive your own class from list:

class mylist(list):
    def removeAll(self,n):
        while n in self:
            self.remove(n)

x = mylist([1,1,2,2,3,3,4,4])
x.removeAll(3)
print(x)
Tim Roberts
  • 48,973
  • 4
  • 21
  • 30
  • Ow my algorithmic complexity. A better version would do a bunch of indexing and (carefully) equal-sized slice assignments. – o11c Jul 29 '21 at 05:17
  • Well, if I were doing this for real, I'd do the inverse: create a new list that only includes the elements I want. The algorithm was not the point; the point was "can we extend the built-in list class". – Tim Roberts Jul 29 '21 at 17:24
-1

I hope that this will help you !

list1 = ["1", "2", "3"]
def operations_on_a_list():
    a = input("Enter the number which you want to delete or remove : ")
    list1.remove(a)
    return list1

if __name__ == '__main__':
    print(operations_on_a_list())