DEV Community

loading...
Cover image for A look at itertools chain method

A look at itertools chain method

teaglebuilt profile image dillan teagle ・1 min read

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.

Discussion (1)

pic
Editor guide
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]