Comprehensions in Python
One of Haskell’s features I really liked was list comprehensions. I created a comparison between Haskell and Julia list comprehensions almost exactly a year ago. It appears that Python list comprehensions are as nice as either Haskell’s or Julia’s! Although, having to use Python’s lambda
form to simulate the more concise Haskell/Julia function definition is less than ideal.
Here is a comparison between the Haskell list comprehensions in “Chapter 5: List Comprehensions” in Graham Hutton’s “Programming Haskell” book and equivalent Python comprehensions.
Haskell | Python |
---|---|
[ x^2 | x <- [1..5] ] |
[ x**2 for x in range(1,6) ] |
[ (x,y) | x <- [1, 2, 3], y <- [4, 5] ] |
[ (x,y) for x in range(1,4) for y in range(4,6) ] |
[ (x,y) | x <- [1..3], y <- [x..3 ]] |
[ (x,y) for x in range(1,4) for y in range(x,4) ] |
concat xss = [ x | xs <- xss, x <- xs ] |
concat = lambda xss: [ x for xs in xss for x in xs ] |
firsts ps = [ x | (x,_) <- ps ] |
firsts = lambda ps: [ x for (x,_) in ps ] |
length xs = sum[ 1 | _ <- xs ] |
length = lambda xs: sum(1 for _ in xs) |
factors n = [ x | x <- [1..n], n `mod` x == 0 ] |
factors = lambda n: [ x for x in range(1,n+1) if n % x == 0 ] |
prime n = factors n == [1, n] |
prime = lambda n: factors(n) == [1, n] |
primes n = [ x | x <- [2..n], prime x ] |
primes = lambda n: [ x for x in range(2, n+1) if prime(x) ] |
find k t = [ v | (k', v) <- t, k == k' ] |
find = lambda k, t: [ v for (k1,v) in t if k == k1 ] |
pairs xs = zip xs (tail xs) |
pairs = lambda xs: zip(xs, xs[1:]) |
sorted xs = and [x <= y | (x,y) <- pairs xs ] |
is_sorted = lambda xs: all(x >= y for (x,y) in pairs(xs)) |
positions x xs = [i | (x',i) <- zip xs [0..n], x == x']
|
positions = lambda x, xs: [ i for (x1,i) in
|
lowers xs = length [x | x <- xs, isLower x ] |
lowers = lambda xs: len([ x for x in xs if x.islower() ]) |
count x xs = length [x' | x' <- xs, x == x'] |
count = lambda x, xs: len([ x1 for x1 in xs if x == x1]) |