0

Right now i have list of tuples as show below:

[(78, -32), (54, -32), (30, -32), (30, -8), (30, 16), (30, 40), (30, 64), (6, 64), (-18, 64), (-42, 64), (-66, 64), (-66, 88), (-90, 88), (-114, 88)]

My current codes are as such:

i = 13 # Let i start at index 13
tech = [] # Define list
while (x, y) != (start_x, start_y): # while loop to iterate through all the coordinates until the path has been found
    tech.append(solution[x,y]) # Appends the coordinates to tech list
    x, y = solution[x, y] # get x and y coordinates

for i in tech: # Loop thorugh each tuple
    print(i) # Print each tuple
    # time.sleep(1)
    i -= 1  # Decrement the index 

What i want to do is to print out the list in reverse order starting with the last tuple coordinates at the front and the first tuple coordinates at the back. The problem now is that when i try to decrement the index it throws this error:

unsupported operand type(s) for -=: 'tuple' and 'int'

Does anybody know why?

Barmar
  • 741,623
  • 53
  • 500
  • 612

4 Answers4

2

You can use slicing to accomplish this!

x = [(78, -32), (54, -32), (30, -32), (30, -8), (30, 16), (30, 40), (30, 64), (6, 64), (-18, 64), (-42, 64), (-66, 64), (-66, 88), (-90, 88), (-114, 88)]

print(x[::-1])

output

[(-114, 88), (-90, 88), (-66, 88), (-66, 64), (-42, 64), (-18, 64), (6, 64), (30, 64), (30, 40), (30, 16), (30, -8), (30, -32), (54, -32), (78, -32)]
Ironkey
  • 2,568
  • 1
  • 8
  • 30
1

you can use .reverse() function by doing it:

data= [(78, -32), (54, -32), (30, -32), (30, -8), (30, 16), (30, 40), (30, 64), 
       (6, 64), (-18, 64), (-42, 64), (-66, 64), (-66, 88), (-90, 88), (-114, 88)]
data.reverse()
print(data)
Patrick Artner
  • 50,409
  • 9
  • 43
  • 69
Jasar Orion
  • 626
  • 7
  • 26
0

Here, i is the variable you are using to iterate over the tech list, so decrementing each tuple by 1 doesn't work, if you want to print the items backwards:

print(*reversed(tech),sep="\n")

Reverse in-place :-)

tech.reverse()

Or use a different variable per iteration (Your intent is to decrement i?):

for x in tech: # Loop thorugh each tuple
    print(x) # Print each tuple
    # time.sleep(1)
    i -= 1  # Decrement the index 
Wasif
  • 14,755
  • 3
  • 14
  • 34
0
l = [(78, -32), (54, -32), (30, -32), (30, -8), (30, 16), (30, 40), (30, 64), (6, 64), (-18, 64), (-42, 64), (-66, 64), (-66, 88), (-90, 88), (-114, 88)]
print(l[::-1])

Using [::-1] will reverse the list values.

Joe Ferndz
  • 8,417
  • 2
  • 13
  • 33
Code GUI
  • 21
  • 2
  • 1
    Please don't post only code as an answer, but also provide an explanation of what your code does and how it solves the problem of the question. Answers with an explanation are usually more helpful and of better quality, and are more likely to attract upvotes. – Yagiz Degirmenci Nov 10 '20 at 17:01