I want to define a class ListWrapper that has all list behaviors and also has a filter method.
It should work like this:
ls = [1, 2, 3, 4, 5]
ls = ListWrapper(ls)
ls.filter(lambda x: True if x % 2 == 0 else False)
print(ls)
# out: [2, 4]
what should I do?
This is my attempt that failed
class ListWrapper(list):
def filter(self, func):
filtered_list = list(filter(func, self))
self = ListWrapper(filtered_list)
ls = [1, 2, 3, 4, 5]
ls = ListWrapper(ls)
ls.filter(lambda x: True if x % 2 == 0 else False)
print(ls)
# out: [1, 2, 3, 4, 5]
>Solution :
To make your implementation work, you can modify the original ListWrapper object in place by removing all its elements and appending the filtered elements using the clear() and extend() methods.
Here’s an updated implementation that should work as expected:
class ListWrapper(list):
def filter(self, func):
filtered_list = list(filter(func, self))
self.clear()
self.extend(filtered_list)
ls = [1, 2, 3, 4, 5]
ls = ListWrapper(ls)
ls.filter(lambda x: True if x % 2 == 0 else False)
print(ls)
# out: [2, 4]