DEV Community

Cover image for A look at itertools chain method

A look at itertools chain method

dillan teagle on October 26, 2019

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 stand...
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]