1
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

3
  • 3
    When you're reaching that level of complexity I would probably not use a list comp for that. A regular loop may be more readable. Also, you shouldn't be using is like that. is checks object equality, not value equality. Commented Sep 19, 2011 at 12:37
  • 1
    Don't use is to compare numbers. Use ==. Commented Sep 19, 2011 at 12:40
  • I see the answer. Here is the point, the second loop runs after the first one. yi is actually 3 in the local scope. If run them alone, the second one will raise an error. Commented Sep 19, 2011 at 12:41

2 Answers 2

7

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.

Sign up to request clarification or add additional context in comments.

Comments

0

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.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.