0

I am trying to create functions for the property list. How do you create the attribute function for something like this?

list([1,2,3,4,5]).even()

should return:

[2,4]

The method should be easy but I am having trouble associating the function with the predefined object list.

4
  • You can't. Python doesn't allow this. Commented May 28, 2015 at 22:56
  • Don't put links to secondary questions that only appear behind a login wall. If you have another question, then ask it. Commented May 28, 2015 at 22:59
  • Do you want to change the original list? Commented May 28, 2015 at 23:03
  • No, i want the function call above to work. Apparently there is a solution but, based on the posts below, i do not think it is possible. The above is one test code. Commented May 28, 2015 at 23:07

2 Answers 2

4

You cannot add methods or attributes to any of the built-in objects. This is by design.

Instead, you can create your own list type that is derived from the built-in one:

class MyList(list):
    def even(self):
        return [x for x in self if x % 2 == 0]

Demo:

>>> 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]

For more information, see Classes in the documentation, specifically the section on Inheritance.

Sign up to request clarification or add additional context in comments.

2 Comments

Or self[:] = (x for x in self if not x % 2) to change the original list,
@PadraicCunningham - Well, the OP said he wanted to have even() return [2, 4]. If the method mutated the list, then it should probably return None instead to be consistent with list.sort() or list.reverse(). That's why I made it return a new list.
4

You can't monkeypatch built in objects in Python like you can in Ruby. You'd have to build a new object, inherit list, and put your method on that.

class MyList(list):
    def even(self):
        return [num for num in self if num % 2 == 0]

MyList([1,2,3,4,5]).even()

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.