1

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.

4
  • check this [int(i) for x in a if x['a'] == 2 for i in x['b'].split(",") ] Commented Oct 9, 2017 at 11:11
  • what are u doing with nested loop ? Commented Oct 9, 2017 at 11:12
  • @pdshah I've updated my question to be more clear at what am I trying to do and what am I trying to achieve. Commented Oct 9, 2017 at 11:23
  • 1
    both [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. Commented Oct 9, 2017 at 13:40

2 Answers 2

2

Turn around your loops in the list comprehension:

 result = [{'year': 1990, 'days_in_mon':'1,2'}, {'year':1991, 'days_in_mon':'2,3'}] def test_fn(li): return [int(i) for x in li if x['year'] == 1991 for i in x['days_in_mon'].split(",")] test_fn(result) # returns [2, 3] 

This is needed, as the first loop is evaluated before the second. So x must be initialized before executing the second one.

The way you wrote it, x is not defined:

print [int(i) for i in x['days_in_mon'].split(",") for x in result if x['year'] == 1991] NameError: name 'x' is not defined 
Sign up to request clarification or add additional context in comments.

Comments

1

what u have:

[int(i) for i in x['days_in_mon'].split(",") for x in result if x['year'] == 1991] Traceback (most recent call last): File "<pyshell#1>", line 1, in <module> [int(i) for i in x['days_in_mon'].split(",") for x in result if x['year'] == 1991] NameError: name 'x' is not defined 

what to be :

>>> [int(i) for x in result if x['year'] == 1991 for i in x['days_in_mon'].split(",") ] [2, 3] 

you write the nested loop in wrong way

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.