0

I'm trying to represent values from a list in a simple graph with tkinter in python. Indexes as X and values as Y. I tried this aproach:

from Tkinter import *

root = Tk()
ls = [1,5,3,4,7,8,3,2,5]
cv = Canvas(root)
for ind,val in enumerate(ls):
    cv.create_line(ind*20,\
                   val*20,\
                   (ind+1)*20,\
                   ls[ind+1]*20)
cv.pack()
root.mainloop()

As you can see, i'm using the index and value from the current item as initial XY and same from the next item in list. This raises the obvious IndexError when the loop reaches the last item and it tries to get ls[ind+1]

With that error in mind, i tried to modify the loop to ignore the last item. Got this:

from Tkinter import *

root = Tk()
ls = [1,5,3,4,7,8,3,2,5]
cv = Canvas(root)
for ind,val in enumerate(ls):
    if ls[ind] is ls[-1]:
        pass
    else:
        cv.create_line(ind*20,\
                       val*20,\
                       (ind+1)*20,\
                       ls[ind+1]*20)
cv.pack()
root.mainloop()

It works... or at least, it doesn't break the program. But if any item has same value as the last one, the loop ignores that cycle. And i'm stuck here. I think this is the simplier aproach, but i cant figure out how ignore that last item.

Aditional info: This is an isolated problem from a bigger program. Lists are not hardcoded so using the index of the last item is not an option.

David P.
  • 125
  • 9
  • If you really just want to skip the last item then `for ind, val in enumerate(ls[:-1]):` – MrAlexBailey Feb 17 '16 at 20:03
  • Your title is way off. The solution to your problem is here [Python: Looping through all but the last item of a list](http://stackoverflow.com/questions/914715/python-looping-through-all-but-the-last-item-of-a-list) – Jasper Feb 17 '16 at 20:05
  • @Jkdc THAT'S IT! Feeling stupid and deserving the negative votes. – David P. Feb 17 '16 at 20:12

0 Answers0