Search code examples
pythonlist-comprehension

Why is this returning an empty list?


Not too sure what I am doing wrong here. I am trying to convert all values in input list to floats. Then print the newly converted values out.

class Data_Manager:
    def __init__(self, input_data):
        self.data = input_data
        self.out_list = []
        self.get_single_data = self.get_single_data(value=self.data)
        
    def get_single_data(self, value):
        try:
            success, value = True, float(value)
        except:
            success, value = False, value
        return success, value
        
    def convert_data(self):
        output_list = [self.get_single_data(value)[1] for value in self.data if self.get_single_data(value)[0]]
        self.out_list.append(output_list)
        return output_list
    
    def display(self):
        return self.out_list


if __name__ == "__main__":
    input_data = ["4.1",22,-12,-1,"25","?",0.55,"w",-3.6,"Z",22.12]
    dm = Data_Manager(input_data)
    print(dm.display())

>>[]

Solution

  • First of all, in line five of your code self.get_single_data = self.get_single_data(value=self.data) you are re-assigning def get_single_data method to the result of the same method which is a tuple. In your if __name__ == "__main__": block when you call the code dm.display() it only returns the self.out_list which is an empty list.

    Now you can call dm.convert_data() method which will do all the operations and populate self.out_list but remember in your __init__ method, you have re-assigned get_single_data method to the output of the same method so when you call convert_data you will get TypeError.

    You can remove this line self.get_single_data = self.get_single_data(value=self.data) in the __init__ method or rename self.get_single_data to a different name.

    Try this solution:

    class Data_Manager:
        def __init__(self, input_data):
            self.data = input_data
            self.out_list = []
    
        def get_single_data(self, value):
            try:
                success, value = True, float(value)
            except:
                success, value = False, value
            return success, value
    
        def convert_data(self):
            output_list = [self.get_single_data(value)[1] for value in self.data if self.get_single_data(value)[0]]
            self.out_list.append(output_list)
            return output_list
    
        def display(self):
            return self.out_list
    
    
    if __name__ == "__main__":
        input_data = ["4.1", 22, -12, -1, "25", "?", 0.55, "w", -3.6, "Z", 22.12]
        dm = Data_Manager(input_data)
        dm.convert_data()
        print(dm.display())
    
    
    [[4.1, 22.0, -12.0, -1.0, 25.0, 0.55, -3.6, 22.12]]