Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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.

like image 846
user1994660 Avatar asked Feb 21 '13 14:02

user1994660


2 Answers

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

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

but iterables can be any iterator that yields the iterables:

def gen_iterables():     for i in range(10):         yield range(i)  itertools.chain.from_iterable(gen_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 an infinite number of finite iterators:

def gen_iterables():     while True:         for i in range(5, 10):             yield range(i)  chain.from_iterable(gen_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.

like image 63
Martijn Pieters Avatar answered Sep 21 '22 11:09

Martijn Pieters


I could not find any valid example ... where I can see the difference between them [chain and chain.from_iterable] and why to choose one over the other

The accepted answer is thorough. For those seeking a quick application, consider flattening several lists:

list(itertools.chain(["a", "b", "c"], ["d", "e"], ["f"])) # ['a', 'b', 'c', 'd', 'e', 'f'] 

You may wish to reuse these lists later, so you make an iterable of lists:

iterable = (["a", "b", "c"], ["d", "e"], ["f"]) 

Attempt

However, passing in an iterable to chain gives an unflattened result:

list(itertools.chain(iterable)) # [['a', 'b', 'c'], ['d', 'e'], ['f']] 

Why? You passed in one item (a tuple). chain needs each list separately.


Solutions

When possible, you can unpack an iterable:

list(itertools.chain(*iterable)) # ['a', 'b', 'c', 'd', 'e', 'f']  list(itertools.chain(*iter(iterable))) # ['a', 'b', 'c', 'd', 'e', 'f'] 

More generally, use .from_iterable (as it also works with infinite iterators):

list(itertools.chain.from_iterable(iterable)) # ['a', 'b', 'c', 'd', 'e', 'f']  g = itertools.chain.from_iterable(itertools.cycle(iterable)) next(g) # "a" 
like image 34
pylang Avatar answered Sep 22 '22 11:09

pylang