0

I have a very simple piece of code in Python 2.7 where I must use a while loop to traverse an index backwards. I am getting a print out where it goes backwards, but my while loop does not stop at the end and therefore produces an out of range error and I do not know why. I am trying to dope it out but failing.

Here is my code:

fruit = 'banana'
print len(fruit)

index = 0
while index <= len(fruit):
    letter = fruit[index - 1]
    print letter
    index = index - 1

What I think is going on here is I am initializing the var index to 0 and then asking python to work with the var fruit while the index is less than or equal to the size of fruit. The problem is when index gets to 0, I have also tried using just < but the way I wrote the code it seems that it still goes beyond 0, I am not sure though.

MCP_infiltrator
  • 3,961
  • 10
  • 45
  • 82

1 Answers1

5

Your index goes from 0, -1, -2... whereas the length is either 0 or positive, once the negative indices go beyond the -len(lst) limit you get an 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 could fix this by initializing the index variable to len(lst) - 1 and iterating until 0.

index = len(test) - 1
while index >=0: 
    # Do Something

Or if you keep your index to 0, then you could change your while loop to

while index > -len(fruit):
    # Do Something

An Alternative - You could use for loop on the reversed list here to iterate over the list in reverse. See the example

>>> testList = [1, 2, 3]
>>> for i in testList[::-1]:
        print i


3
2
1

testList[::-1] is Python's Slice Notation.

Community
  • 1
  • 1
Sukrit Kalra
  • 33,167
  • 7
  • 69
  • 71
  • Actually, it should be `while index > -len(fruit)` to make it working. Your answer is a modified version of the asker's code :) I mean, your answer is all fine but in my opinion it'd be better to show the asker how to make his code work the way he meant it to be. – Maciej Gol Jul 21 '13 at 14:41
  • Yes. I could have changed that too. Added that as an alternative too. :) – Sukrit Kalra Jul 21 '13 at 14:43
  • Thank you, I changed index to `index = len(fruit)-1` and changed inside the loop `letter = index[fruit - 1]` to `letter = index[fruit]` and that fixed it. – MCP_infiltrator Jul 21 '13 at 14:45
  • 1
    Glad to hear. Feel free to accept the answer if it was helpful. :) – Sukrit Kalra Jul 21 '13 at 14:45
  • You could mention about `fruit[::-1]` just in case OP does not know about it, or even using `reversed`. – ersran9 Jul 21 '13 at 14:46
  • @ersran9 : Added that as an alternative. Thanks. :) – Sukrit Kalra Jul 21 '13 at 14:48