If I execute following line of code inside function I get an exception: UnboundLocalError: local variable 'x' referenced before assignment but using the same line of code outside of function runs without any error. Why is that?
result = [{'year': 1990, 'days_in_mon':'1,2'}, {'year':1991, 'days_in_mon':'2,3'}] def test_fn(li): return [int(i) for i in x['days_in_mon'].split(",") for x in li if x['year'] == 1991] test_fn(result) # Gives an error `UnboundLocalError: local variable 'x' referenced before assignment` [int(i) for i in x['days_in_mon'].split(",") for x in result if x['year'] == 1991] # No Error update
Expected result : [2,3]
What am I trying to do here?
I am trying to pull out value of of 'days_in_mon' from certain dict in a list and parse it as a list of numbers.
[int(i) for i in x['days_in_mon'].split(",") for x in result if x['year'] == 1991]and[int(i) for i in x['days_in_mon'].split(",") for x in li if x['year'] == 1991]are same and raising exception inside and outside of function. @Igle's answer is correct. You have wrong implementation of list comprehension.