DEV Community

Cover image for A look at itertools chain method
dillan teagle
dillan teagle

Posted on

A look at itertools chain method

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)]
Enter fullscreen mode Exit fullscreen mode

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
Enter fullscreen mode Exit fullscreen mode

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)
Enter fullscreen mode Exit fullscreen mode

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
Enter fullscreen mode Exit fullscreen mode

I think the chain method gives the flexibility to use this as a default choice for list iteration.

Top comments (2)

Collapse
 
waylonwalker profile image
Waylon Walker • Edited

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 and chain.from_iterables so I opened up a repl and found this.

more itertools flatten

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.

Collapse
 
fernandosavio profile image
Fernando Sávio

I nice way to chain two sequences is unpacking them in a list literal. 😍

a, b = (1, 2), (3, 4)
print([*a, *b])
# [1, 2, 3, 4]