The Python Oracle

Why won't my list populate? IndexError: List Out of Range

--------------------------------------------------
Rise to the top 3% as a developer or hire one of them at Toptal: https://topt.al/25cXVn
--------------------------------------------------

Music by Eric Matyas
https://www.soundimage.org
Track title: Magical Minnie Puzzles

--

Chapters
00:00 Why Won'T My List Populate? Indexerror: List Out Of Range
01:02 Accepted Answer Score 3
02:20 Thank you

--

Full question
https://stackoverflow.com/questions/2012...

--

Content licensed under CC BY-SA
https://meta.stackexchange.com/help/lice...

--

Tags
#python #python3x #stack

#avk47



ACCEPTED ANSWER

Score 3


Unfortunately you operator_stack list is empty therefore it returns a IndexError BTW if you want to find the last element of a list use and make sure to make it to None if its empty:

So use:

peek = operator_stack[-1] if operator_stack else None

instead of:

peek = operator_stack[len(operator_stack)-1]

Also when debugging your code it is clearly visible from the comments that these lines in:

line 49 :while not operator_stack and prec[peek] >= prec[element]:

line 59 : while not operator_stack:

should actually look like:

line 49 :while operator_stack and prec[peek] >= prec[element]:

line 59 : while operator_stack:

Finally add a if statement to check if peek is None

A short version would be

#line 18
peek = operator_stack[-1] if operator_stack else None
#line 49
if peek is not None:
    while operator_stack and prec[peek] >= prec[element]:

            #Append the pop'd element of the operator stack to the
            #output_queue list.
            output_queue.append(operator_stack.pop())

    #Append whatever is left (+,-,*,/) to the operator stack
    operator_stack.append(element)

    #line 59
    while operator_stack:
            #Append the last element in the stack until the stack is empty.
            output_queue.append(operator_stack.pop())

If you doubt what while operator_stack: means, see this simple example:

>>> a = [2,5,6]
>>> while a: # a is not empty right?
...     print 2 # so print 2
...     break # and break
2