There is a question with exactly the same title in stackoverflow but the problem is not what I want to ask. I was solving a leetcode problem and found there is a quite interesting difference between the list comprehension and for loop. Please compare the following two approaches.
Approach 1
set1 = [[]]
num = [1,2,3]
for n in num:
for s in set1:
set1 += [ s + [n] ]
print(set1)
Approach 2
set1 = [[]]
num = [1,2,3]
for n in num:
set1 += [ s + [n] for s in set1]
print(set1)
Approach 1 hangs while Approach 2 does not and produces a correct result. The reason I think is that:
1) Approach 1 adds element to set1 for each member of set1. Thus, the for loop never ends because set1 list is ever growing.
2) Approach 2 updates set1 after all the elements in set1 are processed. Am I on the right track in understanding the difference between two approaches? Also, can I consider [ s + [n] for s in set1] as a list resulted from the following pseudo code?
tmp = []
for s in set1:
tmp += [s + [n]]