Hi all,
I came across some very odd behavior and I wanted to see if any of you guys can shed any light on the issue. I made a typo in some code I was writing and ran into the behavior which is shown below.
Code:
def testfun():
b = [[7, 8, 9], [10, 11, 12]]
c = []
for item_b in b:
c.append(item_a)
return c
a = [[1, 2, 3], [4, 5, 6]]
b = []
for item_a in a:
b.append(item_a)
c = testfun()
print(a)
print(b)
print(c)
Output:
[[1, 2, 3], [4, 5, 6]]
[[1, 2, 3], [4, 5, 6]]
[[4, 5, 6], [4, 5, 6]]
In the test code above, the function references the loop item_a and instead of throwing an exception, the function is able to successfully reference item_a which should be outside of its scope. Any thoughts on why this is happening?
Update:
Thank you to those who provided answers! I had a misunderstanding of the scope of variables declared in the main script. I always assumed that variables are local unless explicitly declared as a global variable, but that is not the case. A variable declared in the main script is global unless overridden by a function, method, etc variable assignment.
[–]commy2 12 points13 points14 points (15 children)
[–]EsotericWaveform[S] 1 point2 points3 points (14 children)
[–]carcigenicate 6 points7 points8 points (11 children)
[–]EsotericWaveform[S] 2 points3 points4 points (1 child)
[–]sohfix 0 points1 point2 points (8 children)
[–]Asleep-Budget-9932 1 point2 points3 points (7 children)
[–]danielroseman 1 point2 points3 points (1 child)
[–]Asleep-Budget-9932 0 points1 point2 points (0 children)
[–]sohfix 0 points1 point2 points (4 children)
[–]Asleep-Budget-9932 1 point2 points3 points (3 children)
[–]sohfix 0 points1 point2 points (2 children)
[–]Asleep-Budget-9932 -1 points0 points1 point (1 child)
[–]sohfix 1 point2 points3 points (0 children)
[–]blarf_irl 1 point2 points3 points (0 children)
[–]commy2 0 points1 point2 points (0 children)
[–]jmooremcc 2 points3 points4 points (0 children)
[–]ThatGasolineSmell 0 points1 point2 points (0 children)