generator / iterator mystery

Dave Abrahams dave at boostpro.com
Sun Mar 13 16:22:26 EDT 2011


Please consider:

>>> from itertools import chain
>>> def enum3(x): return ((x,n) for n in range(3))
... 
>>> list(enum3('a'))
[('a', 0), ('a', 1), ('a', 2)]


# Rewrite the same expression four different ways:

>>> list(chain(  enum3('a'), enum3('b'), enum3('c')  ))
[('a', 0), ('a', 1), ('a', 2), ('b', 0), ('b', 1), ('b', 2), ('c', 0), ('c', 1), ('c', 2)]

>>> list(chain(  *(enum3(x) for x in 'abc')  ))
[('a', 0), ('a', 1), ('a', 2), ('b', 0), ('b', 1), ('b', 2), ('c', 0), ('c', 1), ('c', 2)]


>>> list(chain(  
...    (('a',n) for n in range(3)), 
...    (('b',n) for n in range(3)), 
...    (('c',n) for n in range(3))  ))
[('a', 0), ('a', 1), ('a', 2), ('b', 0), ('b', 1), ('b', 2), ('c', 0), ('c', 1), ('c', 2)]

>>> list(chain(  *(((x,n) for n in range(3)) for x in 'abc')  ))
[('c', 0), ('c', 1), ('c', 2), ('c', 0), ('c', 1), ('c', 2), ('c', 0), ('c', 1), ('c', 2)]

Huh?  Can anyone explain why the last result is different?
(This is with Python 2.6)

Thanks in advance!

-- 
Dave Abrahams
BoostPro Computing
http://www.boostpro.com




More information about the Python-list mailing list