How to sum two list in class(Python)?Ask Questions

 Posted on 14 days ago

Hello,
I have problem, I tried many option to code sum of two list in class... its not working at all Huh

Python Code: 

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?

Share On: facebook gplus twitter
profile
Asked by Merkle Groot on 14 days ago Score: 6 points
Add Comment:

Comments

1 Answers

0 Corrected Answers
Aproved Answers
0
Profile
Answered by Jhon Walls on 11/8/2019 6:46:03 AM Score: 64 points

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:

Python Code:

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))

Comments

Add Comment:

Post Your Answers

Existing Members

Sign in to your account
Email Address
Password
New Member?
Sign up and complete profile
Full Name
Email Address
I have read and agree to the Terms of Service and Privacy Policy
Please subscribe me to the StoodQ newsletters
Guideline to answer a question:

Useful tips to submit your answer
Please read below guidelines before you submit your answer for question.

  • Read and understand question for which you are submitting your answer.
  • Try to avoid grammatical and spell mistake while answering.
  • Do not post any irrelevant information in your answer.
  • Explain your answer with example or any reference link to help who posted question.
  • If you find irrelevant question, please report it to support. Click here to contact support.
  • You agree to the privacy policy and terms of use to submit any contents.

Note: StoodQ is online developers community which helps developer for their difficulty, lets help them with your value contribution.