Crazy9
Crazy9

Reputation: 33

python double for in list comprehension

I have checked the other questions but here I found something very strange.

if I make the two for loop in a list comprehension it works well.

pools = [(0, 1, 2), (0, 1, 2)]
result = [[]]
for pool in pools:
    result = [x + [y] for x in result for y in pool]

# print(result)
# result = [[0, 0], [0, 1], [0, 2], [1, 0], [1, 1], [1, 2], [2, 0], [2, 1], [2, 2]]

But if I break it down into normal nested for loop it will be an endless code.

pools = [(0, 1, 2), (0, 1, 2)]
result = [[]]
for pool in pools:
    for x in result:
        for y in pool:
            result.append(x + [y])

# This will be an endless looping

I guess it may because there are some hidden code in the python list comprehension? Really appreciate for your kindness help.

I have modified the nested for loop but still seems not work.

pools = [(0, 1, 2), (0, 1, 2)]
result = [[]]
temp = [[]]
for pool in pools:
    for x in result:
        for y in pool:
            temp.append(x + [y])
result = temp

# result = [[], [0], [1], [2], [0], [1], [2]]

Upvotes: 0

Views: 272

Answers (1)

Michael Butscher
Michael Butscher

Reputation: 10959

In the first code sample the list comprehension is executed first and the finally created list is assigned to result.

In the second example the list referenced by result is modified while the second for-loop iterates over it. Always appending new items to result in the loop ensures that the for-loop won't ever exhaust the list.

The list comprehension can be rewritten with conventional for-loops as:

pools = [(0, 1, 2), (0, 1, 2)]
result = [[]]
for pool in pools:
    temp = []     # Begin of rewritten list comprehension
    for x in result:
        for y in pool:
            temp.append(x + [y])

    result = temp # Final assignment of constructed list

Upvotes: 1

Related Questions