Fix nested loop for more than 3 elements

- combine flatten list for each nested level instead once at the end