Hacker News new | ask | show | jobs
by thomasahle 3743 days ago
It's equivalent to

  planets_flat = []
  for episode in episodes.values():
    for planet in episode['planets']:
      plants_flat.append(planet)
Notice how the for loops in the comprehension goes in the same order as in the imperative code.
1 comments

> Notice how the for loops in the comprehension goes in the same order as in the imperative code.

Thanks, that's a sane way to explain the order. Up to right now, it was always "the opposite of what you'd expect", which was a memory rule that always failed me.

It also helps on how ifs should be inserted, for example:

  ys = []
  for x in xs:
    if P(x):
      for y in Y(x):
        if Q(x,y):
          ys.append(y)
Becomes

  [y
     for x in xs
     if P(x)
     for y in Y(x)
     if Q(x,y)
  ]
Surely combining this many for/if's may often be the wrong idea. Just like making a depth 4 iterative loop isn't always ideal. It does make the order easier to remember though :)
Which is why you should probably avoid nesting list comprehensions. A normal for loop with a single list comprehension inside it works just as well, and is far easier to read.
It also works with the if-filtering, which usually goes in the inner most loop.

Actually I don't recall if you can put an if between two for's, like you might do in an imperative loop.