Python Forum

Full Version: Sum two list in class
You're currently viewing a stripped down version of our content. View the full version with proper formatting.
Hello,
I have problem, I tried many option to code sum of two list in class... its not working at all Huh
class MyList:
  def __init__(self, a):
    self.a = a

  def __add__(self, other):
    new_list = []
    for i in range(0, len(self.a)):
      new_list.append(self.a[i] + other.a[i]) 
    return MyList(new_list)
It's always print something like that:
Output:
<__main__.MyList object at 0x7f8ef826c3d0>
Do you know what I do badly?
First of all, it would be better if you subclass of Python's list type. In this case, you will not need to intruduce auxiliary variable a.
Take a look at this:

class MyList(list):
  def __add__(self, other):
    if len(self)!= len(other):
        raise ValueError("Lists have different sizes. ")
    else:
        return MyList(a + b for a, b in zip(self, other))
Python is very flexible, so you can create your own types and operations.
Here a example with +, -, *, /, //, %, format()

The __r-Methods__ are used, if the left operand does not support the operation.
If you have on the left side a regular list and want to add it to MyList, the __radd__ method from MyList is used.
Same with other operations.

from operator import (
    add,
    sub,
    mul,
    truediv,
    floordiv,
    mod,
)
from numbers import Number
from itertools import tee


# inherit from list
class MyList(list):
    def __init__(self, iterable=None):
        if not iterable:
            iterable = []
        # tee creates by default from on iterator, two
        # independend iterators
        to_check, iterable = tee(iterable)
        # allows the use of generators,
        # but is not memory efficient
        for element in to_check:
            if not isinstance(element, Number):
                raise TypeError('Only Numbers are allowed')
        # init the list itself
        super().__init__(iterable)

    def _op(self, op, other):
        """
        Helper function to apply the operation on both lists.
        """
        if len(self) != len(other):
            raise TypeError('Lists have different sizes')
        return self.__class__(op(a, b) for a, b in zip(self, other))

    def __add__(self, other):
        return self._op(add, other)

    def __sub__(self, other):
        return self._op(sub, other)

    def __mul__(self, other):
        return self._op(mul, other)

    def __truediv__(self, other):
        return self._op(truediv, other)

    def __floordiv__(self, other):
        return self._op(floordiv, other)

    def __mod__(self, other):
        return self._op(mod, other)

    def __format__(self, fmt):
        """
        Controls the deleimiter used with format method or
        format string
        """
        return fmt.join(map(str, self))


    __radd__ = __add__
    __rsub__ = __sub__
    __rmul__ = __mul__
    __rfloordiv__ = __floordiv__
    __rtruediv__ = __truediv__
    __rmod__ = __mod__



my_list1 = MyList([10,20,30])
my_list2 = MyList([1,2,3])
regular_list1 = [10,20,30]
regular_list2 = [1,2,3]

# __add__, __sub__, ...
print(
    my_list1 + my_list2,
    my_list1 - my_list2,
    my_list1 * my_list2,
    my_list1 / my_list2,
    my_list1 // my_list2,
    my_list1 % my_list2,
)

# __add__, __sub__, ...
print(
    my_list1 + regular_list2,
    my_list1 - regular_list2,
    my_list1 * regular_list2,
    my_list1 / regular_list2,
    my_list1 // regular_list2,
    my_list1 % regular_list2,
)

# __radd__, __rsub__, ...
print(
    regular_list1 + my_list2,
    regular_list1 - my_list2,
    regular_list1 * my_list2,
    regular_list1 / my_list2,
    regular_list1 // my_list2,
    regular_list1 % my_list2,
)


some_result = regular_list1 + my_list2
my_delimiter = ' || '
print(f'{some_result:{my_delimiter}}')