'For' loop symmetry with list comprehensions.

Sean Ross sross at connectmail.carleton.ca
Thu Jul 3 18:34:03 CEST 2003


"Hannu Kankaanpää" <hanzspam at yahoo.com.au> wrote in message
news:840592e1.0307021036.508d7d7d at posting.google.com...
> One can currently say this with list comprehensions:
>
> [x.lower() for x in words if x.startswith('foo')]
>
> Wouldn't it be better if the normal 'for' syntax was symmetrical
> with the notation used in list comprehensions?

If we were trying to be symmetrical, then:

>>> words = ("hello", "bonjour")
>>> otherwords = ("foo", "bar")
>>> msgs = ["%s %s"%(x,y) for x in words for y in otherwords]
>>> msgs
['hello foo', 'hello bar', 'bonjour foo', 'bonjour bar']


(being symmetrical) we should also be able to write:

>>> msgs = []
>>> for x in words:
...  for y in otherwords:
...   msgs.append("%s %s"%(x,y))
...
>>> msgs
['hello foo', 'hello bar', 'bonjour foo', 'bonjour bar']


as follows:

msgs = []
for x in words for y in otherwords:
    msgs.append("%s %s"%(x,y))


If you really want symmetry, well, this is symmetrical. Do you want this as
well?

-0
Sean






More information about the Python-list mailing list