Bug in list comprehensions?
Duncan Booth
duncan.booth at invalid.invalid
Wed Jun 7 06:39:42 EDT 2006
Iain King wrote:
>>>> [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?
[x for x in y for y in beta] is a shorthand for:
tmp = []
for x in y:
for y in beta:
tmp.append(x)
So x iterates over whatever y is before the loop starts, and y iterates
over beta (but that doesn't affect what x is iterating over).
The important thing is to remember that the order of 'for' and 'if'
statements is the same as though you had written the for loop out in full.
More information about the Python-list
mailing list