Pythonにはリスト内容表記がある。for~in~を使ってこうやって書く:
>>> [x*x for x in [1,2,3,4,5]] [1, 4, 9, 16, 25]
表記こそ違うけどやってることはHaskellのリスト内包表記とおなじだ。
forは複数つけることもできる:
>>> [(x,y) for x in [1,2,3,4,5] for y in [1,2,3,4,5]] [(1, 1), (1, 2), (1, 3), (1, 4), (1, 5), (2, 1), (2, 2), (2, 3), (2, 4), (2, 5), (3, 1), (3, 2), (3, 3), (3, 4), (3, 5), (4, 1), (4, 2), (4, 3), (4, 4), (4, 5), (5, 1), (5, 2), (5, 3), (5, 4), (5, 5)]
これは次の二重のforと同じ。
>>> r = [] >>> for x in [1,2,3,4,5]: ... for y in [1,2,3,4,5]: ... r.append((x,y)) ... >>> r [(1, 1), (1, 2), (1, 3), (1, 4), (1, 5), (2, 1), (2, 2), (2, 3), (2, 4), (2, 5), (3, 1), (3, 2), (3, 3), (3, 4), (3, 5), (4, 1), (4, 2), (4, 3), (4, 4), (4, 5), (5, 1), (5, 2), (5, 3), (5, 4), (5, 5)]
さらに、ifを使って条件を制限できる:
>>> [(x,y) for x in [1,2,3,4,5] for y in [1,2,3,4,5] if x <= y] [(1, 1), (1, 2), (1, 3), (1, 4), (1, 5), (2, 2), (2, 3), (2, 4), (2, 5), (3, 3), (3, 4), (3, 5), (4, 4), (4, 5), (5, 5)]