Python Forum
Thread Rating:
  • 0 Vote(s) - 0 Average
  • 1
  • 2
  • 3
  • 4
  • 5
Sum two list in class
#1
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?
Reply
#2
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))
Reply
#3
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}}')
Almost dead, but too lazy to die: https://sourceserver.info
All humans together. We don't need politicians!
Reply


Possibly Related Threads…
Thread Author Replies Views Last Post
  Generating a list to feed into a class object zizi 0 1,461 Nov-02-2018, 01:50 PM
Last Post: zizi

Forum Jump:

User Panel Messages

Announcements
Announcement #1 8/1/2020
Announcement #2 8/2/2020
Announcement #3 8/6/2020