Skip to content Skip to sidebar Skip to footer

Python For Loop Appending Only Last Value To List

I have a loop that is setting the values of one list to the value of another and while I am able to achieve this with my current code it is only appending the last grouping of valu

Solution 1:

updated_values = []

should be outside loop just after def statement, otherwise you overwrite values added to the list in every iteration.


defupdate_raw_data_sheet(data_set):
    updated_values = []
    # ...

Solution 2:

This is exactly what you programmed. You reset updated_values on each iteration of the outer loop, which wipes out the previous values:

for col_val, col_name inzip(gs_columns, columns):
    updated_values = [] # List storing the combined list values

If you want all three iterations` of data, then you need to lift the initialization out of the loop:

updated_values = [] # List storing the combined list values
for col_val, col_name in zip(gs_columns, columns):

Post a Comment for "Python For Loop Appending Only Last Value To List"