Ad

How Do I Refer To An Element In A Nested List Within A For-loop?

I have a nested list of coordinates [[x1, y1],[x2, y2],[x3,y3]...].

I want to use a for-loop in order to determine the distance in the x-direction between two consecutive points. I want to do the same thing for the y-direction later. This is my attempt so far:

p1=[X1, Y1]
p2=[X2, Y2]
p3=[X3, Y3]
p4=[X4, Y4]
p5=[X5, Y5]
coordiantes = [p1, p2, p3, p4, p5]
    
for i in coordinates:
            p1_x = i[0]
            p2_x = i[0]+1
            p1_y = i[1]
            p2_y = i[1]+1
            distance_x = p2_x - p1_x

Apparently, i[0]+1 doesn't give you the subsequent x-value in the next list but adds 1 to the first x-value.

My question is how do I refer to the subsequent x-value in my nested list? So, if i referred to p1, I also want to get p2 in that loop.

I also tried adding another variable j and assigning it j = i + 1 so that I can refer to the subsequent x-value by using j[0]. However, I get the error that one cannot concatenate list to int.

Thank you in advance!

Ad

Answer

for i in coordinates is a for-each loop. You don't have access to the current index, i is directly the list child.

You should loop using range or enumerate if you want to access the adjacent item by incrementing current index. For example,

for ind in range(len(coordinates)-1):
            p1_x = coordinates[ind][0]
            p2_x = coordinates[ind+1][0]
            p1_y = coordinates[ind][1]
            p2_y = coordinates[ind+1][1]
            distance_x = p2_x - p1_x

The range limit is len-1 because we don't want to process the last element (ind+1 would be out of bounds).

Ad
source: stackoverflow.com
Ad