Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Using instance method to concatenate a list

I have a class named stock, and I am trying to concatenate quarterly earnings for an object.

class Stock :
    def __init__(self,name,report_date,earning,estimate):
        self.Name = name
        self.Report_date = report_date
        self.Earning = [earning]
        self.Estimate = estimate
    def list_append(self,earning):
        self.Earning = [self.Earning,earning]
example = Stock('L',2001,10,10)
example.list_append(11)
example.list_append(12)
example.list_append(13)

Like this.
So that finally i want the output of example.Earning = [10,11,12,13].
But the output is coming out as example.Earning = [[[[10], 11], 12],13]
I tried the following.

self.Earning = (self.Earning).append(earning)
Error = "int" does not have attribute append

and

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

self.Earning[-1:] = earning

But they are throwing me errors.
How can I get rid of this embedded list([[[10], 11], 12]) and make just one list([10,11,12,13])?

>Solution :

To solve your problem and get rid of the embedded lists, you can do:

def list_append(self,earning):
        self.Earning = [*self.Earning,earning]

The * will spread the old list self.Earnings and adds earning to a new list and assign it to self.Earning

Or just simply use method append:

def list_append(self,earning):
    self.Earning.append(earning)
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading