Traverse through an index variable backwards, Python -
i have simple piece of code in python 2.7 must use while loop traverse index backwards. getting print out goes backwards, while loop not stop @ end , therefore produces out of range error , not know why. trying dope out failing.
here code:
fruit = 'banana' print len(fruit) index = 0 while index <= len(fruit): letter = fruit[index - 1] print letter index = index - 1 what think going on here initializing var index 0 , asking python work var fruit while index less or equal size of fruit. problem when index gets 0, have tried using < way wrote code seems still goes beyond 0, not sure though.
your index goes 0, -1, -2... whereas length either 0 or positive, once negative indices go beyond -len(lst) limit out of bounds error.
>>> test = [1, 2, 3] >>> test[-1] 3 >>> test[-2] 2 >>> test[-4] traceback (most recent call last): file "<pyshell#75>", line 1, in <module> test[-4] indexerror: list index out of range you fix initializing index variable len(lst) - 1 , iterating until 0.
index = len(test) - 1 while index >=0: # or if keep index 0, change while loop to
while index > -len(fruit): # an alternative - use for loop on reversed list here iterate on list in reverse. see example
>>> testlist = [1, 2, 3] >>> in testlist[::-1]: print 3 2 1 testlist[::-1] python's slice notation.
Comments
Post a Comment