# [Python-Dev] List comprehension syntax

**Huaiyu Zhu
**
HZhu@knowledgetrack.com

*Fri, 14 Jul 2000 18:42:11 -0700 (PDT)*

I just read the whole thread on list comprehension. Here's my proposed
syntax, given by examples. This notation is very safe as it has been used
in mathematics for years.
a = [1, 2, 3]; b = [4, 5, 6]
#----------------------------------------------------
# Parallel loops:
c = tuples(a,b) # c = [(1,4), (2,5), (3,6)]
c = lists(a,b) # c = [[1,4], [2,5], [3,6]]
c = xtuples(a,b) # c = ((1,4), (2,5), (3,6))
c = xlists(a,b) # c = ([1,4], [2,5], [3,6])
#----------------------------------------------------
# prefix x has the same effect as in xrange in loops
for pair in xtuples(a,b):
print pair # print (1,4); print (2,5); print (3,6)
for pair in xtuples(a,b):
print pair # print [1,4]; print [2,5]; print [3,6]
for i, j in xlists(a,b): pass
#----------------------------------------------------
# list comprehension - all elements that satisfy conditions
c = [x*2, y: x, y in xtuples(a,b)] # c = [(2,4), (4,5), (6,6)]
c = [[x, y]: x, y in xtuples(a,b)] # c = [[1,4], [2,5], [3,6]]
c = [x: x in a+b; x%2=0] # c = [2, 4, 6]
c = [x in a+b: x%2=0] # ditto
c = [x,y: x, y in xtuples(a,b); x>1; x+y<8] # c = [(2,5)]
c = [x,y in xtuples(a,b): x>1; x+y<8] # ditto
#----------------------------------------------------
# Corresponding to old syntax
c = [x in a: f(x)] # c = filter(f, x)
c = [f(x): x in a] # c = map(f, a)
#----------------------------------------------------
# Iterated loops (all elements that satisfy condition):
c = [x, y: x in a; y in b] # c = [(1,4), (1,5), (1,6), (2,4), (2,5), ...]
c = [[x,y]: x in a; y in b] # c = [[1,4], [1,5], [1,6], [2,4], [2,5], ...]
for i, j in [i, j: i in a; j in b]:
print i, j # print 1,4; print 1,5; ...
for i in a; j in b:
print i, j # ditto
--
Huaiyu Zhu hzhu@users.sourceforge.net
Matrix for Python Project http://MatPy.sourceforge.net