Question about itertools module

129 views
Skip to first unread message

Huan Wang

unread,
Mar 23, 2015, 6:20:15 PM3/23/15
to python-g...@googlegroups.com
Hi everyone,

I am trying to use the itertools module following the Python documentation, but I got some questions about it.

The Python documentation (https://docs.python.org/2/library/itertools.html ) shows some examples like: 
chain('ABC', 'DEF')      --> A B C D E F
imap(pow,(2,3,10), (5,2,3)) --> 32 9 1000

However, the results are not the same as shown in the website. 

The version of Python I am running is 2.7.9,  and my codes are:

>>> import itertools
>>> itertools.chain('ABC', 'DEF')
<itertools.chain object at 0x0000000002A4B390>
>>> a = itertools.chain('ABC', 'DEF')
>>> a
<itertools.chain object at 0x0000000002A4B2E8>
>>> print a
<itertools.chain object at 0x0000000002A4B2E8>

>>> itertools.imap(pow, (2,3,10),(5,2,3))
<itertools.imap object at 0x0000000002A4B198>
>>> b = itertools.imap(pow, (2,3,10), (5,2,3))
>>> b
<itertools.imap object at 0x0000000002A4B240>
>>> print b
<itertools.imap object at 0x0000000002A4B240>
>>> 

I do not know why the outputs would not be able to print as   'A B C D E F' and  32 9 100.

Could someone help me to understand it? 

Cheers,

Huan
.



Huan Wang

unread,
Apr 3, 2015, 3:39:14 PM4/3/15
to python-g...@googlegroups.com
Hi, 

I finally found the way to show the elements of my case in the question I asked.
The itertools module created an object NOT a list as shown in the returned information in Python IDE, like
<itertools.chain object at 0x0000000002A4B390> or <itertools.imap object at 0x0000000002A4B240>

To "print" the elements in the object, I should use for loop to go through it, like 

>>> import itertools
>>> a = itertools.chain('ABC''DEF')
>>> for i in a:
............print i

A
B
C
C
D
E

>>> b = itertools.imap(pow, (2,3,10), (5,2,3))
>>> for j in b:
...........print j

32
9
64
>>>

Huan
..

在 2015年3月24日星期二 UTC+2上午12:20:15,Huan Wang写道:
Reply all
Reply to author
Forward
0 new messages