mike991 mike991 - 18 days ago 4x
Python Question

How can I rewrite this list comprehension as a for loop?

How can I rewrite this using nested for loops instead of a list comprehension?

final= [[]]
for i in array_list:
final.extend([sublist + [i] for sublist in final])

return final


If you try to iterate over final as you extend it, it creates an infinite loop. Because every time you go to the next element, you add another element, so you never reach the end of the list.

If you want to do the inner loop as a for loop instead of a list comprehension, you need to iterate over a copy of final.

final = [[]] 
for i in [1, 2, 3]:
    for sublist in final[:]:
        final.extend([sublist + [i]])