how to explain this loop result in python?
x=range(1,4)
y=range(1,4)
[(xi,yi) for xi in x for yi in y if xi is yi]
#output
# [(1, 1), (2, 2), (3, 3)]
[(xi,yi) for xi in x if xi is yi for yi in y ]
#output, I am confused about this one
#[(3, 1), (3, 2), (3, 3)]
Can any one explain why the second loop results like this?
I am quite开发者_运维技巧 confused about how multiple in-line loops work in Python.
Also, any tutorial on python in-line loops is favored
The second construct isn't valid code on its own:
In [1]: x=range(1,4)
In [2]: y=range(1,4)
In [3]: [(xi,yi) for xi in x if xi is yi for yi in y ]
---------------------------------------------------------------------------
NameError Traceback (most recent call last)
/home/aix/<ipython console> in <module>()
NameError: name 'yi' is not defined
The yi
in xi is yi
isn't referring to the yi
that comes after that. It's referring to a pre-existing variable called yi
(at least that's what happens during the very first iteration).
The only reason the code worked for you was that you had previously run the first construct and that had left behind yi
(set to 3
) in the global namespace.
Here is the point, the second loop runs after the first one, when I operated this.
yi is actually 3 in the local scope.
If running them alone, the second one will raise an error.
精彩评论