I would like to extend the list functionality, so we can used as below. How can add this methods to the list object?
# list([1,2,3,4,5]).even() should return [2,4]
I would like to extend the list functionality, so we can used as below. How can add this methods to the list object?
# list([1,2,3,4,5]).even() should return [2,4]
You can't monkey patch list
because it is defined in C extension modules and is therefore inmutable in this sense. You can subclass list:
class mylist(list):
def even(self):
return [x for x in self if x % 2 == 0]
>>> mylist([1,2,3,4,5]).even()
[2, 4]