0

Additionally onto my other post. If I have a list of coordinates, how can I assign them to variables and keep appending and assigning:

positions = [(1,1), (2,4), (6,7)]
index = 0
for looper in range(0, len(positions)):
    posindex = positions[index]
    index = index + 1

Where posindex is pos0, then pos1, then pos2 and increases with the variable index, which will give me the index in the list as well. Python gives me this:

"'posindex' is undefined"

Anyway to put a variable into another one? Any other problems I may run into?

Community
  • 1
  • 1
rollorox202
  • 41
  • 1
  • 1
  • 4

1 Answers1

8

This code works just fine. However, there's a better way:

positions = [(1,1), (2,4), (6,7)]
for posindex in positions:
    # do something with posindex, for example:
    print (posindex)

which outputs

(1, 1)
(2, 4)
(6, 7)

You don't need a loop index - Python can simply iterate over the list. If you do need the index for some other reason, here's how you do it in Python:

for index, posindex in enumerate(positions):
    print ("{0} is at position {1}".format(posindex, index))
Tim Pietzcker
  • 328,213
  • 58
  • 503
  • 561