how can I turn this list comprehension into for loops

70 views Asked by At

I was looking at itertools.product, and in the explanation is a function meant to explain how the function kinda works. It looks like all the magic happens here, in a loop through the lists: result = [x+[y] for x in result for y in list]. So I decided to try to create a couple loops so I can more easily follow exactly what is going on. I modified 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 was expecting. However when I tried to break it down into for loops, I ended up getting tripped up with the looping through result while modifying it (which I read you shouldn't do). 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 the list comprehension with loops in this case?

1

There are 1 answers

2
Bhargav Rao On BEST ANSWER

Add a temporary list that holds your intermediate lists. This is because the list comprehension completely executes and then re-writes the value of result.

A 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.