Re:Python List Comprehensions Explained Visually
by ebola1717 on Wednesday December 02, 2015 @11:13PM
(#10667711)
I've written a fair share of Haskell, and I still get tripped up by list comprehensions in python - even my own. It's not that it's impossible to understand, and when there's only one predicate, I think it's fine:
for row in [[i*j for i in range(1, 8)] for j in some_list if j % 2 == 0]:
some_op(row)
vs
for j in some_list:
if j % 2 == 0:
row = [ i * j for i in range(1,8) ]
some_op(row)
I would compare it to sentences and paragraphs. The former feels like a run-on sentence, while the latter is more obvious, cause it has one predicate per line. Also, list comprehensions are a bit like yoda-speak - it introduces the verb before the subject. You have to untangle the order of operations, rather than having the order read top-down and left-right.
Though definitely need to do something about that second line.
Haskell list comprehensions are a bit easier to parse because they have symbolic delimiters, the fact that Haskell is naturally more terse, and because you can always check the type of the list
Of course, I'm a rubyist, so I'd prefer:
Though definitely need to do something about that second line.Haskell list comprehensions are a bit easier to parse because they have symbolic delimiters, the fact that Haskell is naturally more terse, and because you can always check the type of the list