# [Tutor] IndexError: list index out of range

Michael Langford mlangford.cs03 at gtalumni.org
Thu Sep 20 02:22:16 CEST 2007

```You should check if the stack is empty before you access it:

def popNum(num):
if len(stackA) > 0 and num == stackA[-1]:
stackA.pop()
#etc

--Michael

--
Michael Langford
Phone: 404-386-0495
Consulting: http://www.TierOneDesign.com/
Entertaining: http://www.ThisIsYourCruiseDirectorSpeaking.com

On 9/19/07, bhaaluu <bhaaluu at gmail.com> wrote:
>
> Greetings,
> I'm working with Python 2.4.3 on the GNU/Linux platform.
> I'm currently playing with functions and stacks, and am
> using the "Towers of Hanoi" as a test game to play with.
> Note: This game is not a recursive programming exercise,
>        it is meant to be solved by the player, manually.
>
> The game asks for a number to move, and a stack to move it to.
> The game starts out in this state:
> =========================
> A [5, 4, 3, 2, 1] False
> B [] True
> C [] True
> =========================
> Enter number and stack to move it to: 1b
>
> It seems to work fine with my test moves:
>
> 1b 2c 1c 3b 1a 2b 1b 1b 4c 1c 2a 1a 3c 1b 2c 1c 5b
> Which brings the game to this state:
>
> Enter number and stack to move it to: 5b
> 5 B
> A [] True
> B [5] False
> C [4, 3, 2, 1] False
> =========================
>
> Then, in the second round of test moves, it bombs on the first move:
>
> Enter number and stack to move it to: 1b
> 1 B
> Traceback (most recent call last):
>   File "funcStack.py", line 73, in ?
>     moveNum(num,abc)
>   File "funcStack.py", line 52, in moveNum
>     popNum(num)
>   File "funcStack.py", line 32, in popNum
>     if num == stackA[-1]:
> IndexError: list index out of range
>
> The second round of test moves are:
> 1b 2a 1a 3b 1c 2b 1b 4a 1a 2c 1c 3a 1b 2a 1a 5c
> The third round of test moves are:
> 1b 2c 1c 3b 1a 2b 1b 1b 4c 1c 2a 1a 3c 1b 2c 1c
> Which should bring the game to this state:
> =========================
> C [] True
> B [] True
> A [5, 4, 3, 2, 1] False
> =========================
>
> Here is my Python source code:
> # funcStacks.py
> # passing parameters, returning values, pushing and popping
> # 2007-09-19
> # b h a a l u u at g m a i l dot c o m
> ######################################
> """
> Pseudocode
> 1. Get the number to move and the column to move it to: 1b, 2c, etc.
> 2. Find the column the number is in: A, B, or C
> 3. Is it the last number (ie. can it be popped?) num == stackA[-1]
> 4.   If the number can be popped, pop it!        stackA.pop()
> 5.   Else, number is buried: return an error and try again.
> 6. Determine if the number can be legally moved to the column requested.
> 7.   If the column is empty, move the number:    stackB.append(num)
> 8.   If the column has a number, is it larger?   stackB.append(num)
> 9.   Else if number in column is smaller,  return an error and try again.
> 10. Loop.
> """
> num = 0
> abc = ""
> EMPTY = []
> stackA = []
> stackB = []
> stackC = []
>
> def isEmpty(stack):
>     if stack == EMPTY:
>         return True
>     else:
>         return False
>
> def popNum(num):
>     if num == stackA[-1]:
>         stackA.pop()
>     elif num == stackB[-1]:
>         stackB.pop()
>     elif num == stackC[-1]:
>         stackC.pop()
>     else:
>         return "Error: number not available."
>
> def pushNum(num,abc):
>     if abc == 'C':
>         stackC.append(num)
>     elif abc == 'B':
>         stackB.append(num)
>     elif abc == 'A':
>         stackA.append(num)
>     else:
>         return "Move not allowed, try again."
>
> def moveNum(num,abc):
>     popNum(num)
>     pushNum(num,abc)
>     return stack_status()
>
> def stack_status():
>     print "A",stackA, isEmpty(stackA)
>     print "B",stackB, isEmpty(stackB)
>     print "C",stackC, isEmpty(stackC)
>
> # main
> print '='*25
> stackA=[5,4,3,2,1]
> stack_status()
> print '='*25
>
> myMove = raw_input('Enter number and stack to move it to: ')
> while myMove != 'Q':
>     num = int(myMove[0])
>     abc = str.upper(myMove[1])
>     print num, abc
>     moveNum(num,abc)
>     print '='*25
>     myMove = raw_input('Enter number and stack to move it to: ')
>
> Remember, I'm learning Python. I haven't studied OOP yet, so
> suggestions to make a class out of it won't help me much. =)
> --
> bhaaluu at gmail dot com
> _______________________________________________
> Tutor maillist  -  Tutor at python.org
> http://mail.python.org/mailman/listinfo/tutor
>
-------------- next part --------------
An HTML attachment was scrubbed...
URL: http://mail.python.org/pipermail/tutor/attachments/20070919/d6f90df7/attachment.htm
```

More information about the Tutor mailing list