user1994660 user1994660 - 1 month ago 15
Python Question

What is the difference between chain and chain.from_iterable in itertools?

I could not find any valid example on the internet where I can see the difference between them and why to choose one over the other.

Answer

The first takes 0 or more arguments, each an iterable, the second one takes one argument which is expected to produce the iterables:

itertools.chain(list1, list2, list3)

iterables = [list1, list2, list3]
itertools.chain.from_iterable(iterables)

but iterables can be any iterator that yields the iterables.

def generate_iterables():
    for i in range(10):
        yield range(i)

itertools.chain.from_iterable(generate_iterables())

Using the second form is usually a case of convenience, but because it loops over the input iterables lazily, it is also the only way you can chain a infinite number of finite iterators:

def generate_iterables():
    while True:
        for i in range(5, 10)
            yield range(i)

itertools.chain.from_iterable(generate_iterables())

The above example will give you a iterable that yields a cyclic pattern of numbers that will never stop, but will never consume more memory than what a single range() call requires.