😡 Reduce the number of nested loops in Python code

Dmytro Parfeniuk
2 min readJul 20, 2022

--

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

Nested loops

✅ Then, we can easily reduce the number of nested loops by using itertools.chain

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

Complex House with Flats data 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:

Find 2 and more rooms using itertools.chain

✅ 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).

Iterate using one-line for loops
itertools.chain and one-line for loops

✅ And in the end, using conditions to avoid the last indentation if we need:

👉🏻 So, in terms of using functions we may have:

👨🏻‍🎓 Before:

Using nested loops

👨🏻‍🏫 After:

--

--

Responses (5)