A Q. on pop().

Collapse
This topic is closed.
X
X
 
  • Time
  • Show
Clear All
new posts
  • spencer

    #1

    A Q. on pop().

    Hi,
    The code.

    def buildStackMajor ():
    for node in dirStackMinor:
    #print 's is the node...', node
    dirStackMajor.a ppend(node)
    dirStackMinor.p op()
    print 'POP the stack...', len(dirStackMin or)
    print 'after pop...', dirStackMinor

    When I start the "for" loop I have 11 members in
    the stack- a list. The pop() is poping member
    from the back, as though it's deal with a LIFO
    stack instead of LIFO. I never get pass a length
    of 5.
    first Q.. Why is pop() starting from the back
    back of the stack?
    second Q.. Why can't I never empty the stack?
    Thanks.

  • Duncan Booth

    #2
    Re: A Q. on pop().

    spencer wrote:
    [color=blue]
    > first Q.. Why is pop() starting from the back
    > back of the stack?[/color]

    Because that is what it does. Try reading the documentation:
    [color=blue][color=green][color=darkred]
    >>> help(list.pop)[/color][/color][/color]
    Help on method_descript or:

    pop(...)
    L.pop([index]) -> item -- remove and return item at index (default
    last)

    [color=blue]
    > second Q.. Why can't I never empty the stack?[/color]

    Because you are modifying a list while iterating over it which is never a
    good idea. What you have now pops items from the end of the loop so it
    stops about half way along. If you change it to pop item 0 then it will
    shift the items down and your iteration will end up skipping over about
    half of them.

    Try something like this:

    def buildStackMajor ():
    while dirStackMinor:
    dirStackMajor.a ppend(dirStackM inor.pop(0))

    although in that case you might just as well get rid of the loop entirely:

    dirStackMajor += dirStackMinor
    del dirStackMinor[:]

    Comment

    Working...