guthrie wrote: > I'm pretty new to Python, and trying to parse the grammar. > > Q: What is the scope of the testlist in a list_for? > > For example; > Instead of; > for x in [ x in dict if dict[x]=="thing" ]: > in this: > for x in dict and dict[x]=="thing": > x is undefined.
In the above two examples, x is a regular variable (global or local depending on whether it's in a function). It will remain undefined until the first time something gets assigned to it. In your first example (where you appear to have left out a for), it get bound inside the list comprehension, after evaluating 'dict' but before evaluating the test 'dict[x]=="thing"'. I doubt the second example does what you want it to, but here's what happens. Python tries to evaluate the expression 'dict and dict[x]=="thing"' first, before assigning anything to x. Because that expression uses x, you get an undefined error. If it hadn't had the undefined error, it would have tried to iterate over the result (which would have been True or False), which would have raised a TypeError exception. > And why doesn't this work: > for x in dict if dict[x]=="thing": Because it would would just be another way to spell: for x in dict: if dict[x] == "thing: Yes, we've heard all the arguments before. The Python language designers like to have only one way to do things when they can, and in this case they felt that none of the objections (an extra level of indentation or unsightly continue) warranted a new spelling. I recall there was to be a (prerejected) PEP submitted about this recently, but it doesn't appear to be up. > Any insights/hints on why it is broken? It's not broken :) Carl Banks -- http://mail.python.org/mailman/listinfo/python-list