How can I turn this list comprehension into loops
I was looking at itertools.product and there is a function in the explanation intended to explain how the kinda function works. It looks like all this magic is happening here, in a loop through lists: result = [x + [y] for x and result for y in the list]. So I decided to try and create a couple of loops so that I could more closely follow what was going on. I changed the example function to this:
lists = [[1, 2], [3, 4], [5, 6]]
result = [[]]
for l in lists:
result = [x+[y] for x in result for y in l]
print result
And the result is what I expected. However, when I tried to break it into loops, I ended up running into the result of looping when changing it (which I read, you shouldn't). My attempt:
lists = [[1, 2], [3, 4], [5, 6]]
result = [[]]
for l in lists:
for i in result:
for y in l:
result.append([i+[y]])
print result
How would you recreate a list comprehension using loops in this case?
source to share
Add a temporary list containing your intermediate lists. This is because the complete description is fully executed and then overwrites the value result
.
Small code can be demonstrated as follows
result = [[]]
for l in lists:
tmp = []
for x in result:
for y in l:
tmp.append(x+[y])
result = tmp
This will print the same value as required.
source to share