Firstly, lets put it straight: Loops aren’t bad. But when you’re applying transformations inside them, it can lead to long bloated conditional codes.
In such cases, it’s important to not ignore built-in functions like
reduce() that are already at our disposal. More importantly, Python provides List comprehensions which is easily the most Pythonic way of replacing for loops.
Nested for loops is another quintessential case of code smell. Python programmers can easily fall prey for them when doing pattern matching or running more than one iterables together. The following code would start looking ugly once you add a few more lines in it:
for x in listA:
for y in listB:
itertools not only gives a performance boost but is also flat and clean. Just look how clean the above code would look with
for x, y in itertools.product(listA, listB):
product above, we can also pass it in other high order functions easily.
When iterating over multiple lists simultaneously, using the
zip() function is a good idea too(alongwith
enumerator if you need index).