The python itertools module is a collection of tools for handling iterators. I want to make an honest effort to break the habit of repetitive standard patterns of basic python functionality. For example...
We have a list of tuples.
a = [(1, 2, 3), (4, 5, 6)]
In order to iterate over the list and the tuples, we have a nested for loop.
for x in a: for y in x: print(y) # output 1 2 3 4 5 6
I have decided to challenge myself to start using all that itertools has to offer in my every day solutions. Today lets take a look at the chain method!
This first approach will only return the two tuples as as index 0 and 1. Instead of nesting another loop, lets apply the chain method.
from itertools import chain a = [(1, 2, 3), (4, 5, 6)] for _ in chain(a, b): print(_) # output (1, 2, 3) (4, 5, 6)
now we have access to iterate over the tuples without nesting another iteration with a for loop.
for _ in chain.from_iterable(a): print(_) # output 1 2 3 4 5 6
I think the chain method gives the flexibility to use this as a default choice for list iteration.