Assigning Variables to Tuples in a List

124 Views Asked by At

I am currently using a function to return a list of tuples (coordinates). I need to assign these coordinates variables so I can use them in a for loop.

My function is:

new_connect = astar.get_path(n1x, n1y, n2x, n2y)

with print(new_connect) I get the output:

[(76, 51), (75, 51), (74, 51), (73, 51), (72, 51), (71, 51), (70, 51), (69, 51), ...]

I need to assign these tuples variables i.e. (x, y)
So they can be used in the following for loop:

for x in range(new_connect):
    for y in range(new_connect):
        self.tiles[x][y].blocked = False
        self.tiles[x][y].block_sight = False

Which (should) plot the coordinates and change their tile values.

Any help is greatly appreciated. I've been stuck working on this and feel like I'm missing something super simple.

2

There are 2 best solutions below

1
On BEST ANSWER

You can use unpacking

new_connect = [(76, 51), (75, 51), (74, 51), (73, 51), (72, 51), (71, 51), (70, 51), (69, 51)]
for x, y in new_connect:
    print(x, y)
1
On

So, it isn't clear how range(new_connect) is actually working. It shouldn't. You should receive a TypeError, because a list object is not the correct argument to range.

That said, you should be able to create a for loop for a list of tuples by performing the tuple unpacking in the for statement itself.

for x, y in astar.get_path(...):
    ...