Reputation: 11
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
Upvotes: 0
Views: 80
Reputation: 2475
This code also seems to give the same results as your code.
final = [[]]
for i in array_list:
for sublist in list(final):
final.extend([sublist + [i]])
return final
It seems like your code takes the elements of the last iteration and combines them with the element of the current iteration (See 'Example' below). In order to do this with a traditional for loop, you need to prevent the list that is being looped over from being updated while looping. I do this by breaking the link with the 'final' list variable. This can be done with the list() function or by slicing it (then you would need to replace with as proposed by Morgan).
Example
For the array_list of [1,2,3] you get the following. Each line (except for the lines) is a new element of the 'final' list variable.
[]
--------------------------------
1 > array_list[0]
--------------------------------
2 > array_list[1]
1, 2 > array_list[0] + array_list[1]
--------------------------------
3 > array_list[2]
1, 3 > array_list[0] + array_list[2]
2, 3 > array_list[1] + array_list[2]
1, 2, 3 > array_list[0] + array_list[1] + array_list[2]
Upvotes: 0
Reputation: 9986
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]])
Upvotes: 2
Reputation: 60954
Your solution looks to be a very good for
loop one. A one-liner using itertools
is possible, but ugly
list(itertools.chain(list(itertools.combinations(arr, i)) for i in range(len(arr) + 1)))
EDIT:
Prettier:
list(itertools.chain(*[itertools.combinations(arr, i) for i in range(len(arr)+1)]))
Upvotes: 0