In Python, can I define an instance method map() for the list class?
Question: I was hoping to define an instance method `map()` or `join()` for the list
class (for array). For example, for `map()`:

    
    
    class list:
        def map(self, fn):
            result = []
            for i in self:
                result.append(fn(i))
            return result
    
    print [1, 3, 5].map(str)
    

Is it possible in Python to do that for the `list` class? (if not, can the
last line `[1, 3, 5].map(str)` be made to work?)


Answer: Your code creates a new variable called `list`, which hides the original. You
can do a little better by inheriting:

    
    
    class mylist(list):
        def map(self, fn):
            result = []
            for i in self:
                result.append(fn(i))
            return result
    
    mylist([1, 3, 5]).map(str)
    

Note that it is not possible to override `[]` to generate anything other than
a `builtins.list`

* * *

So that leaves monkeypatching the builtin. [There's a module for
that](https://github.com/clarete/forbiddenfruit), `forbiddenfruit`, which in
its own words:

> may lead you to hell if used on production code.

If hell is where you're aiming for, then this is what you want:

    
    
    from forbiddenfruit import curse
    def list_map(self, fn):
        result = []
        for i in self:
            result.append(fn(i))
        return result
    curse(list, "map", list_map)
    
    
    
    print [1, 3, 5].map(str)
    

