'UnboundLocalError: local variable referenced before assignment #

Having issue with the code, I'm getting error with this code for using class and method. Please explain me the error I'm facing.

class Solution():
    def __init__(self,list1,list2):
        self.list1=list1
        self.list2=list2
    def medianOfList(self):
        self.list1=list1
        self.list2=list2
        list1=list1+list2
        l=len(list1)
        sum=0
        for i in range(l):
            sum+=list1[i]
        return sum/l
list1=[1,2]
list2=[3,100]
m=Solution(list1,list2)
m.medianOfList()
UnboundLocalError                         Traceback (most recent call last)
Input In [18], in <module>
     19 list2=[3,100]
     20 m=Solution(list1,list2)
---> 21 m.medianOfList()

Input In [18], in Solution.medianOfList(self)
      9 def medianOfList(self):
---> 10     self.list1=list1
     11     self.list2=list2
     12     list1=list1+list2

UnboundLocalError: local variable 'list1' referenced before assignment


Solution 1:[1]

The variable list1 is indeed not defined within the scope of the medianOfList method. It is only defined in the global scope and as a member of the Solution class as self.list1.

I think the accepted answer doesn't exactly follow your intent. I suppose you'd like to use the members of the object you just initialized as follows instead of adding arguments to the method. (You're by the way computing the mean, not the median, check the difference here for example). Note that the medianOfList() method should be called without any arguments as in your original code.

class Solution():
    def __init__(self, list1, list2):
        self.list1 = list1
        self.list2 = list2
    def medianOfList(self):
        listA = self.list1 + self.list2
        l = len(listA)
        sum = 0
        for i in range(l):
            sum += listA[i]
        return sum/l 

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 jmon12