pythonpython-3.xwhile-loop

Different Variable in while loop


Is it possible to save a value on different variable in a while loop?

For example this is my code

category = [] #differs depending on the input of user
var1 = []
var2 = []
var3 = []

i = []
max_count = len(category)
while i < max_count:
    for ms_division in market_share_division:
        ms_division_df = df3[df3['Geography'] == ms_division]
        ms_product_df = ms_division_df[ms_division_df['Product'] == category[i]]
        ms_df_4 = ms_product_df[ms_product_df['Time Period'].str.contains('L 4', na=False, case=False)]
        ms_df_4 = ms_df_4.head(1)
        if len(ms_df_4)>0:
            ms_df_row_1 = ms_df_4.iloc[0]
            var1.append(ms_df_row_1['Dollar Sales'])

But what i want to do is after the 1st loop, I want to save the next data on the var2 and so on and so forth.


Solution

  • As others have pointed out, you may want to use a list of lists instead of var1, var2, var3 ....

    The following might help you change your code:

    variables = [[], [], []]
    
    i = 0
    while i < 9:
        # some computations
        variables[i % 3].append(i) # here you would append your real data instead of ´i´
        i += 1
    
    print(variables)
    

    which results in:

    [[0, 3, 6], [1, 4, 7], [2, 5, 8]]
    

    Showcasing the fact that in each iteration, the next nested list is written to.

    Finally, after the loop, instead of var1 you have your data in variables[0] and so on.