Search code examples
pythonobjectconcatenationinstance

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

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)