Language Design: list_for scope?

Larry Bates larry.bates at websafe.com
Fri Jul 21 13:02:42 EDT 2006


First things first:

Don't name a variable "dict" because if you do it shadows
the built in dict function (same goes for list, str, ...).
This WILL bite you later, so start now by not naming
variables by any built in names.

Now to your question:

for x in <something>: requires <something> be an iterable
(e.g. list, tuple, iterable class instance, etc) so there
is something that it can loop over one object at at time.

>for x in [ x in dict if dict[x]=="thing" ]:

needs to be written (if I'm understanding what you are
doing) as:

for x in [x for x in d if d[x]=="thing"]:

[ x for x in dict if dict[x]=="thing" ] is a list
comprehension that will resolve to a list of keys from the
dictionary where the values are "thing".  This way
the result of the list comprehension is a list which is
something the outside for loop can iterate over.

Example:

>>> d={1:'x',2:'thing',3:'thing',4:'thing',5:'thing', \
   6:'z',7:'thing',8:'thing',9:'y'}

>>> [x for x in d if d[x]=="thing"]
[2, 3, 4, 5, 7, 8]

-Larry Bates


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.
> 
> And why doesn't this work:
>     for x in dict if dict[x]=="thing":
> 
> Any insights/hints on why it is broken?
> 
> Thanks,
> Gregory
> ----------------------------------------
> http://docs.python.org/ref/grammar.txt:
> list_for ::=
>              "for" expression_list "in" testlist
>               [list_iter]
> testlist ::=
>              test ( "," test )* [ "," ]
> list_iter ::=
>              list_for | list_if
> list_if ::=
>              "if" test [list_iter]
> 
> 
> ----== Posted via Newsfeeds.Com - Unlimited-Unrestricted-Secure Usenet
> News==----
> http://www.newsfeeds.com The #1 Newsgroup Service in the World! 120,000+
> Newsgroups
> ----= East and West-Coast Server Farms - Total Privacy via Encryption =----



More information about the Python-list mailing list