Home > other >  Creating a list from the class attributes - Python
Creating a list from the class attributes - Python

Time:05-08

I was wondering if someone could elaborate on exactly why creating a new list out of the two attributes passed in the class returns a "NoneType"?

class Finance:
    
    def __init__(self, market = '^GSPC', tickers = []):
        
        self.market = market
        self.tickers = tickers
        self.final_list = self.tickers.insert(0,self.market)


x = Finance(tickers = ['AMZN', 'AAPL'])

type(x.final_list)

I have found a way to create a list of these two by using

[value for value in self.__dict__.values()]

but I just feel like there should be a more elegant way of doing it.

CodePudding user response:

Well, i have tried using Python 3.10 but I’m pretty sure that the insert list method is in place and doesn’t return a value. So my advice is to change the code this way:

import copy
class Finance:
    def __init__(self, market = '^GSPC', tickers = []):
        self.market = market
        self.tickers = tickers
        self.tickers.insert(0,self.market)
        self.final_list = copy.deepcopy(self.tickers)

Now you have a deep copy of the modified list in the variable instance final_list

  • Related