Strange behavior with iterables - is this a bug?

Inyeol Lee inyeol.lee at siliconimage.com
Tue May 30 17:33:19 EDT 2006


On Tue, May 30, 2006 at 01:11:26PM -0700, akameswaran at gmail.com wrote:
[...]
> >>> ================================ RESTART
> >>> f1 = open('word1.txt')
> >>> f2 = open('word2.txt')
> >>> f3 = open('word3.txt')
> >>> print [(i1.strip(),i2.strip(),i3.strip(),) for i1 in f1 for i2 in f2 for i3 in f3]
> [('a', 'a', 'a'), ('a', 'a', 'b'), ('a', 'a', 'c')]
> >>> l1 = ['a\n','b\n','c\n']
> >>> l2 = ['a\n','b\n','c\n']
> >>>
> >>> l3 = ['a\n','b\n','c\n']
> >>> print [(i1.strip(),i2.strip(),i3.strip(),) for i1 in l1 for i2 in l2 for i3 in l3]
> [('a', 'a', 'a'), ('a', 'a', 'b'), ('a', 'a', 'c'), ('a', 'b', 'a'),
> ('a', 'b', 'b'), ('a', 'b', 'c'), ('a', 'c', 'a'), ('a', 'c', 'b'),
> ('a', 'c', 'c'), ('b', 'a', 'a'), ('b', 'a', 'b'), ('b', 'a', 'c'),
> ('b', 'b', 'a'), ('b', 'b', 'b'), ('b', 'b', 'c'), ('b', 'c', 'a'),
> ('b', 'c', 'b'), ('b', 'c', 'c'), ('c', 'a', 'a'), ('c', 'a', 'b'),
> ('c', 'a', 'c'), ('c', 'b', 'a'), ('c', 'b', 'b'), ('c', 'b', 'c'),
> ('c', 'c', 'a'), ('c', 'c', 'b'), ('c', 'c', 'c')]
> 
> explanation of code:  the files word1.txt, word2.txt and word3.txt are
> all identical conataining the letters a,b and c one letter per line.
> The lists I've added the "\n" so that the lists are identical to what
> is returned by the file objects.  Just eliminating any possible
> differences.

You're comparing file, which is ITERATOR, and list, which is ITERABLE,
not ITERATOR. To get the result you want, use this instead;

>>> print [(i1.strip(),i2.strip(),i3.strip(),)
        for i1 in open('word1.txt')
        for i2 in open('word2.txt')
        for i3 in open('word3.txt')]

FIY, to get the same buggy(?) result using list, try this instead;

>>> l1 = iter(['a\n','b\n','c\n'])
>>> l2 = iter(['a\n','b\n','c\n'])
>>> l3 = iter(['a\n','b\n','c\n'])
>>> print [(i1.strip(),i2.strip(),i3.strip(),) for i1 in l1 for i2 in l2 for i3 in l3]
[('a', 'a', 'a'), ('a', 'a', 'b'), ('a', 'a', 'c')]
>>>


-Inyeol Lee



More information about the Python-list mailing list