Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

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 :

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

Your error: UnboundLocalError: local variable 'list1' referenced before assignment was coming because you have not defined list1 in medianOfList(self) but you are trying to access it.

Here’s my solution:

class Solution():
    def __init__(self,list1,list2):
        self.list1=list1
        self.list2=list2
    def medianOfList(self,list1,list2):
        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(list1,list2)
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading