Search code examples
pythonlistvectorlinear-algebrabinary-operators

Can I manually redefine addition and multiplication for Python lists?


I'm working with vectors for small experiments and prototypes in Python. I would like to redefine binary operators like + * - / for Python lists and numbers to mean vector addition, inner product and so on.

I know this is possible with numpy.array or a custom object, but for a small experimental program this makes my code and output cluttered and hard to read.

For example, I want to be able to write:

u=[1,3]
v=[2,-1]
w=2*u+3*v

and have w be the list [8,3]. Is this possible in Python?


Solution

  • You could define a function, such as the following:

    def my_add(u, v):
        u = [2*i for i in u]
        v = [3*i for i in v]
        add = [u[i] = v[i] for i in range(2)]
        return add
    
    u = [1, 3]
    v = [2, -1]
    print(my_add(u, v)) # returns [8,3]
    

    If you want to define your own data type and define its own operators, you can use something called operator overloading. The following is an example:

    class Vector:
        def __init__(self, array):
            self.array = array
    
        def __add__(self, o):
            self.array = [2*i for i in self.array]
            o.array = [3*i for i in o.array]
            return [self.array[i] + o.array[i] for i in range(2)]
    
    u = Vector([1, 3])
    v = Vector([2, -1])
    print(u+v) # returns [8,3]