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])?
CodePudding user response:
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)
CodePudding user response:
The nested lists occur this way because in the initialization of self.Earning = [earning]
you store each "earning" from an int into a list and later store a list into a list. you could simply rewrite the list_append function.
def list_append(self, earning):
self.Earning.append(earning)