I'd like to update an element in a nested list from output in a loop. However, I can't figure out how to do so without clunky nested for-loops. I suspect use of zip
will be necessary, but haven't figure out how to work it in.
I have an empty nested list that I want to fill as the loop progresses:
empty_list = [[], [], []]
I have a separate nested list, with the same number of elements as lists in empty_list
:
lst = [[x], [y], [z]]
I would like to then generate some output from a loop for each element in lst
. My desired result is:
no_longer_empty_list = [[[x], [output_x_1], [output_x_2]],
[[y], [output_y_1], [output_y_2]],
[[z], [output_z_1], [output_z_2]]]
where output_x_1
and output_x_2
are the outputs from the loop when the element being parsed in the loop is x
(and the same for y
and z
)
Here is what I have constructed so far in pseudo-code:
for elem in lst:
if condition holds:
generate output_1
append output_1 to appropriate spot in empty_list
elif other condition holds:
generate output_2
append output_2 to appropriate spot in empty_list
Where I am struggling is how to append the outputs to the right list in the empty_list
.
Apologies if the syntax/explanation is confusing, I've tried to distill it to an understandable format, but will do my best to explain if it is still unclear
Let's assume you have 2 functions; generate_out1()
and generate_out2()
as well as a list with elements x, y, z, where each element can be a list.
result = []
lst = [x, y, z]
for elem in lst:
temp = [elem]
temp.append(generate_out1(elem))
temp.append(generate_out2(elem))
result.append(temp)