Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

__add__ all elements of a list

Tags:

python

I'd like to combine a list of class instances of a class for which the __add__ method is defined.

i.e., I have a list of class instances L=[A,B,C,D] and I want their sum E = A+B+C+D, but generalized so that instead of the + syntax I could do something like E = sum(L).

What function should I use to do that? Is the __add__ method adequate, or do I need to define a different class method (e.g. __iadd__) in order to accomplish this?

(if this turns out to be a duplicate, how should I be asking the question?)

like image 594
keflavich Avatar asked Feb 26 '12 19:02

keflavich


3 Answers

import operator
reduce(operator.add, L)
like image 184
Karoly Horvath Avatar answered Oct 14 '22 10:10

Karoly Horvath


sum may want to add numerical values to instances of your class. Define __radd__ so for example int + Foo(1) will be defined:

class Foo(object):
    def __init__(self, val):
        self.val = val
    def __add__(self, other):
        return self.val + other.val
    def __radd__(self, other):
        return other + self.val

A = Foo(1)
B = Foo(2)
L = [A,B]
print(A+B)
# 3

print(sum(L))
# 3
like image 26
unutbu Avatar answered Oct 14 '22 11:10

unutbu


Ignore my previous answer, it was wrong.

The reduce function allows you to apply any binary function or method to all the elements of a sequence. So, you could write:

reduce(YourClass.__add__, sequence)

If not all objects in the sequence are instances of the same class, then instead use this:

import operator
reduce(operator.add, sequence)

Or this:

reduce(lambda x, y: x + y, sequence)
like image 38
Taymon Avatar answered Oct 14 '22 12:10

Taymon