😡 Reduce the number of nested loops in Python code
One thing that is really annoying is when you have any kind of nested collections you’d like to iterate through.
👉🏻 In that example, we have the House data model that we use in the list of grouped houses. I’d like to print all houses form lists inside
✅ Then, we can easily reduce the number of nested loops by using itertools.chain
⚠️ But actually, it doesn’t work in the example when the House data model is not so simple. Let’s create another example
👉🏻 I’d like to iterate through all flats inside all houses and find only 2 rooms more. So it is possible only by creating a nested loop like this:
✅ And here, using for loops we can achieve the same but without additional indentation for nested loop (I.S. much better for long functions/methods).
✅ And in the end, using conditions to avoid the last indentation if we need:
👉🏻 So, in terms of using functions we may have:
👨🏻🎓 Before:
👨🏻🏫 After: