top | item 27764229

(no title)

berlinquin | 4 years ago

I can make sense of nested Python list comprehensions if I read them as shorthand for nested for loops, in which case you need to define variables in the outer loop before you can define dependent variables in the inner loop.

e.g. with your example above,

  for xs in xss:
      for x in xs:
          x
What's confusing about the syntax is that `x` in your example above comes first, whereas in actual nested loops it comes last. So maybe:

  [for xs in xss for x in xs : x]
Could be alternative syntax that moves `x` to the end?

discuss

order

shirogane86x|4 years ago

That's actually how list comprehensions work in F#: that would become:

  [for xs in xss do for x in xs -> x]
(where -> is a shorthand for do yield) in practice (after 3 years of professional F#), when writing functional code i'd actually rather have the result first rather than last. I got used to reading code right to left with Haskell so that's what feels most natural to me