My question is about Python List Comprehension readability. When I come across code with complex/nested list comprehensions, I find that I have to re-read them several times in order to understand the intent.
Is there an intuitive way to read aloud list comprehensions? Seems like I should start "reading" from the middle, then read the if conditions (if any), and read the expression last.
Here's how I would read the follow line of code aloud, in order to understand it:
[(x, y) for x in [1,2,3] for y in [3,1,4] if x != y]
"For each element in List x, and each element in List y, if the two elements are not the same, create a list of tuples."
Two examples that I am struggling with: How would you read the following List Comprehensions aloud?
From another question in Stack Overflow:
[x for b in a for x in b]Python docs has this example:
[[row[i] for row in matrix] for i in range(4)]
Any suggestions or pointers for ways to read aloud list comprehensions such that the intention becomes clearer is much appreciated.
[... for ... in A for ... in B]pattern forms a cartesian product; the[... for ... in [... for ... in A]]forms a pipeline (as in shell pipes); and the[[... for ... in A] for ... in B]creates a multidimensional array. After categorizing the looping's general form, interpreting the expression and if-condition part becomes trivial. - Lie RyanS = {(x, y) : x ∈ {1,2,3} and y ∈ {3,1,4}, x != y}. In more complex examples it's not very helpful, though. - OfirD