0

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]
Leonardo
  • 2,484
  • 2
  • 25
  • 37
  • 2
    You can't (well, without rewriting Python's source code). You're better off subclassing `list`. –  Dec 15 '14 at 23:18
  • You could do somersaults, maybe the good point is to point to the following . – nbro Dec 15 '14 at 23:21
  • 1
    You can [add](http://stackoverflow.com/questions/972/adding-a-method-to-an-existing-object) methods to objects though. – Marcin Dec 15 '14 at 23:22
  • 1
    @Marcin But not to lists, because they are implemented in C. – Daniel Roseman Dec 15 '14 at 23:24
  • You can either subclass `list` or create a utility function that takes the list and manipulate it the way you want. – Addison Dec 16 '14 at 01:27

1 Answers1

1

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]
elyase
  • 39,479
  • 12
  • 112
  • 119