Ad

Python - Appending Values To A List

- 1 answer

In the code below, each x has 9 values of y. I want new_gamesplyed = [x, y1, y2, y3, y4, y5, y6, y7, y8, y9]. But in the list 'difference' all 292 values are getting stored at once.

new_gamesplayed = []
difference = []

col_count = df_gamesplayed.shape[1]-1 = 9
l = len(df_gamesplayed) = 292

for x in range(len(df_gamesplayed)):      
    for y in range (1, col_count):
        diff = abs(df_gamesplayed.iloc[x, y] - df_gamesplayed.iloc[x, y + 1])        
        difference.append(diff)
    new_gamesplayed.append([df_gamesplayed.iloc[x, 0], difference])    
Ad

Answer

You are using the same difference variable across entire code snippet so it is no wonder that it stores all values that were passed to it by append

If i correctly understand you need to "reset" the container between some statements in main loop. So i suggest to reinitialize the bucket collection every time at the main loop statements start. Example:

for x in range(len(df_gamesplayed)):      
    d_temp = []  # <---------  reset it here ----------
    for y in range (1, col_count):
        diff = abs(df_gamesplayed.iloc[x, y] - df_gamesplayed.iloc[x, y + 1])        
        d_temp.append(diff)
    new_gamesplayed.append([df_gamesplayed.iloc[x, 0], d_temp])
Ad
source: stackoverflow.com
Ad