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.
Top comments (2)
I am a big fan of replacing nested loops with itertools/more itertools. I often use more_itertools.flatten, I was curios what the difference was between
flatten
andchain.from_iterables
so I opened up a repl and found this.I'll argue that
flatten
is more readable and likely that folks will understand what it is doing intuitively when they read my code, but it comes at the cost of an extra dependency.I nice way to chain two sequences is unpacking them in a list literal. 😍