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.Of course, I'm a rubyist, so I'd prefer:
some_list.select { |j| j % 2 == 0 }
.map { |j| (1..8).map { |i| i * j } }
.map { |row| some_op(row) }
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
[ [i*j | i <-[1..8]] | j <- [1..4], j % 2 == 0 ]
I disagree: code should be correct before it is clear. And because it's so easy to mess up a for loop (for me at least), I choose list comprehensions where reasonable.
> you're just being a jerk to the next dev that has to read your code
That's not very charitable to either party. You're assuming that the motive of the author is to be a jerk, and you're assuming that the reader won't understand. If I had a dev on my team who couldn't read a list comprehension, I'd (a) wonder how they were hired, and then (b) teach them.