Reputation: 9213
I have a function in which I would like to pass list comprehension to as an input. I'm getting an error about my_list not being defined. I know I could put my_list
outside the function, but in reality that list is generated as part of the function.
The actual definition is complex so here is simplified example:
def my_def(list_comp):
global my_list
my_list = [[1,2],[3,4]]
list_comp_output = list_comp
return list_comp_output
print my_def([x[1] for x in my_list])
Upvotes: 2
Views: 5619
Reputation: 14360
That's because my_list is not defined;)
First you have to realize that the body in the function definition (however if there were default arguments, these would have been evaluated right away) is not executed until the function is actually call, but the argument to it is evaluated before the function is called.
The two first statements in it says first that the symbol my_list
is that of the global scope in this function. The second says to assign to that symbol (in global scope) the value [[1,2],[3,4]]
. But this does as mentioned not happen before the function is called (so right after the function definition it is still not defined).
The consequence of this is that you try to evaluate my_list
(when calling the function) before it is defined or assigned to (in the function body).
You could try to make it happen by calling my_def([])
first, which will define my_list
, but the correct way would probably be to put the definition of my_list
outside the function definition:
my_list = [[1,2],[3,4]]
def my_def(list_comp):
list_comp_output = list_comp
return list_comp_output
print my_def([x[1] for x in my_list])
Which gives the answer:
[2, 4]
Upvotes: 1
Reputation: 107287
Actually all we have in Python is runtime; there is no such thing as a separate compile time1.(in the scope of interpreter). and the functions are not exception from this rule.
So what you have done here is defining my_list
as a global variable and attempt to use it in a list comprehension, when python doesn't defined such thing.
You can just run your function 1 time then use that list comprehension :
def my_def(list_comp):
global my_list
my_list = [[1,2],[3,4]]
list_comp_output = list_comp
return list_comp_output
my_def([])
print my_def([x[1] for x in my_list])
[2,4]
Also i don't see any thing logical here :) if you want to use a global variable just define if in the scope of your module (out side the function and pass it to your function.)
def my_def(list_comp):
# do stuff with list_comp
return list_comp_output
my_list= # a costume list
li=[x[1] for x in my_list]
print my_def(li)
Or more elegant do the list comprehension within your function :
def my_def(list_comp):
return [x[1] for x in list_comp]
1. Learning Python by Mark Lutz
Upvotes: 2