Search code examples
pythonnested-loops

For loop only goes through one iteration in python


stat_to_grid_dist = []
for a in xrange(99):
    stat_to_grid_dist_colm = []
    for k in xrange(22):
        stat_to_grid_dist_row = []
        for l in xrange(28):
            stat_to_grid_dist_row.append(math.sqrt(
                math.pow(x_station[a]-xpt_grid[k],2) +
                math.pow(y_station[a]-ypt_grid[l],2)
            ))
        stat_to_grid_dist_colm.append(stat_to_grid_dist_row)
    stat_to_grid_dist.append(stat_to_grid_dist_colm)

When using the above, the first for loop (the a for loop) only moves through the loop once. I can access anything in the stat_to_grid_dist list for the stat_to_grid_dist[0][k][l], and when I put a print statement for a anywhere in the loop it only outputs zero. I can't seem to figure out what is happening. Am I incorrectly understanding how to append to a list of list of lists?


Solution

  • This will print out a 99 times. I don't know anything about your data though:

    import math
    
    x_station = range(1,100)
    y_station = range(1,100)
    xpt_grid = range(1,23)
    ypt_grid = range(1,29)
    
    stat_to_grid_dist = []
    for a in xrange(99):
        stat_to_grid_dist_colm = []
        for k in xrange(22):
            stat_to_grid_dist_row = []
            for l in xrange(28):
                stat_to_grid_dist_row.append(
                math.sqrt(math.pow(x_station[a]-xpt_grid[k],2) + 
                math.pow(y_station[a]-ypt_grid[l],2)))
            stat_to_grid_dist_colm.append(stat_to_grid_dist_row)
        stat_to_grid_dist.append(stat_to_grid_dist_colm)
        print a