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])
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 :
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.)
Or more elegant do the list comprehension within your function :
1. Learning Python by Mark Lutz