I'm experiencing some counterintuitive behavior on nested list comprehensions
data = 'what is wrong with the nested iterator'
[ (u, i) for i in xrange(0,len(u),1) for u in [ v for v in data.split(' ')]]
what I was hoping is that the nested loop would iterate over the range of characters for each word in the first loop. What is happening however is that it seems to be looping the string array first, and iterate on the last value of u
:
[('what', 0), ('is', 0), ('wrong', 0), ('with', 0), ('the', 0), ('nested', 0), ('iterator', 0), ('what', 1), ('is', 1), ('wrong', 1), ('with', 1), ('the', 1), ('nested', 1), ('iterator', 1), ('what', 2), ('is', 2), ('wrong', 2), ('with', 2), ('the', 2), ('nested', 2), ('iterator', 2), ('what', 3), ('is', 3), ('wrong', 3), ('with', 3), ('the', 3), ('nested', 3), ('iterator', 3), ('what', 4), ('is', 4), ('wrong', 4), ('with', 4), ('the', 4), ('nested', 4), ('iterator', 4), ('what', 5), ('is', 5), ('wrong', 5), ('with', 5), ('the', 5), ('nested', 5), ('iterator', 5), ('what', 6), ('is', 6), ('wrong', 6), ('with', 6), ('the', 6), ('nested', 6), ('iterator', 6), ('what', 7), ('is', 7), ('wrong', 7), ('with', 7), ('the', 7), ('nested', 7), ('iterator', 7)]
To understand these nested type of list comprehensions you could imagine them as two nested for-loops like this:
result = []
for i in xrange(0,len(u),1):
for u in [ v for v in data.split(' '):
result.append((u, i))
with the order of both loops preserved. From this it should be pretty clear that you need to switch their positions in order to get the desired result.