I am currently converting a script from Python 2 to Python 3. While debugging it, I stumbled upon a part of the code that behaves differently between both versions. However, I am unable to explain this difference.
Here is a reproducer:
variable_1 = "x"
variable_2 = "y"
list_of_variables = ['variable_1', 'variable_2']
existing_variables = vars()
print([variable for variable in list_of_variables if variable in vars()])
print([variable for variable in list_of_variables if variable in existing_variables])
Python 2.7.18 shows the following output:
['variable_1', 'variable_2']
['variable_1', 'variable_2']
Whereas Python 3.9.0 displays:
[]
['variable_1', 'variable_2']
Why is the first list comprehension not working in Python 3? And why is it working when storing the content of vars() within a variable?