itertools.chain to chain an iter list?

user478514 picture user478514 · Mar 8, 2011 · Viewed 12k times · Source
import itertools
def _yield_sample():
    it = iter(itertools.combinations('ABCD', 2))
    it2 = iter(itertools.combinations('EFGH', 3))
    itc = itertools.chain(it,it2)
    for x in itc:
        yield x

def main():
    for x in _yield_sample():
        print x

This works to print the combinations.

>>> 
('A', 'B')
('A', 'C')
('A', 'D')
...

But this:

def __position_combination(_count = [2,3,4,5]):
    its = []
    for ct in _count:
        it = iter(itertools.combinations('ABCDEFG', ct))
        its.append(it)
    itc = itertools.chain(its)
    for x in itc:
        yield x

def main():
    for x in __position_combination():
        print x

will not, it will print out

>>> 
<itertools.combinations object at 0x02179210>
<itertools.combinations object at 0x02179240>
<itertools.combinations object at 0x02179270>

I have to rewrite code to make it works as demanded.

itc = itertools.chain(*its)

Here is my question:

itertools.chain(iter, iter, iter)  vs    itertools.chain(*[iter,iter,iter])

What is the different between them? According to documentation the itertools.chain does:

def chain(*iterables):
    # chain('ABC', 'DEF') --> A B C D E F
    for it in iterables:
        for element in it:
            yield element

So, why does itertools.chain(iter, iter, iter) also works here?
Does it means iter, iter, iter = *(iter, iter, iter) ?