Bug in list comprehensions?

Iain King iainking at gmail.com
Wed Jun 7 06:22:03 EDT 2006


I was playing with list comprehensions, to try and work out how doubled
up versions work (like this one from another thread: [i for i in
range(9) for j in range(i)]).  I think I've figured that out, but I
found something strange along the way:

>>> alpha = ["one", "two", "three"]
>>> beta = ["A", "B", "C"]
>>> [x for x in alpha for y in beta]
['one', 'one', 'one', 'two', 'two', 'two', 'three', 'three', 'three']
>>> [x for x in y for y in beta]
['C', 'C', 'C']
>>> beta = [alpha, alpha, alpha]
>>> beta
[['one', 'two', 'three'], ['one', 'two', 'three'], ['one', 'two',
'three']]
>>> [x for x in y for y in beta]
['C', 'C', 'C']
>>> [y for y in beta]
[['one', 'two', 'three'], ['one', 'two', 'three'], ['one', 'two',
'three']]
>>> [x for x in y for y in beta]
['one', 'one', 'one', 'two', 'two', 'two', 'three', 'three', 'three']

Shoudn't both lines '[x for x in y for y in beta]' produce the same
list?
I'm guessing I'm the one confused here... but I'm confused!  What's
going on?

Iain




More information about the Python-list mailing list