List comprehensions
Dan Schmidt
dfan at harmonixmusic.com
Mon Dec 20 14:21:48 EST 1999
mlh at vier.idi.ntnu.no (Magnus L. Hetland) writes:
| P = [(x, y) for x in X for y in Y]
|
| Hm... Do the iterators work in parallel? Or would I end up with a
| Cartesian product here? Logically (or intuitively), the above
| expression would seem (to me) to mean:
|
| P = []
| for x in X:
| for y in Y:
| P.append((x,y))
|
| which is, come to think of it, exactly what it means. Cool! But what
| could the version with "and" mean, then? Since it is a bit more
| verbose, it should probably be something less often used... Hm. It
| seems to me to mean something like:
|
| P = []
| for i in range(min(len(X),len(Y))):
| x, y = X[i], Y[i]
| P.append(x,y)
You know, I'm only half kidding when I say that the syntax for that
second type of loop should be
P = [(x, y) for x in X while y in Y]
--
Dan Schmidt | http://www.dfan.org
More information about the Python-list
mailing list