Hacker Newsnew | past | comments | ask | show | jobs | submitlogin

Two nested loops is ugly but tolerable, 3+ is disgusting. Refactor it so you don’t have to go 3 deep.


What method would you use to iterate over a list of lists?


It definitely doesn't solve all cases, but quite a lot of nested loops can be eliminated with `itertools.chain`:

  for item in itertools.chain.from_iterable(list_of_lists):
      # Do something with item


A list of lists is two deep, while not preferable two nested loops is probably going to be the solution but if I can come up with another, I would rather use that. Like, perhaps a function to process the row instead of two loops in a single function.


If you have a function with a loop to iterate the inner list and place that function within another loop iterating the outer list, isn't that the same thing?

What would you have the inner function do?




Guidelines | FAQ | Lists | API | Security | Legal | Apply to YC | Contact

Search: