Removing from a List in Place

Collapse
This topic is closed.
X
X
 
  • Time
  • Show
Clear All
new posts
  • Gregory Piñero

    #1

    Removing from a List in Place

    I'm going to assume that it's supposed to work like this, but could
    someone tell me the reasoning behind it? I.E. why is 3 skipped?
    >>alist=[1,2,3]
    >>for item in alist:
    .... print item
    .... if item==2:
    .... alist.remove(it em)
    ....
    1
    2
    >>>
    Bonus Question:
    Can we make this behave more intuitiviely in Python 3000?

    -Greg


    --
    Gregory Piñero
    Chief Innovation Officer
    Blended Technologies
    (www.blendedtechnologies.com)
  • bayerj

    #2
    Re: Removing from a List in Place

    I'm going to assume that it's supposed to work like this, but could
    someone tell me the reasoning behind it? I.E. why is 3 skipped?
    Because:
    >>alist[2]
    3

    You are removing the third item, not the second.

    Comment

    • John Machin

      #3
      Re: Removing from a List in Place

      bayerj wrote:
      I'm going to assume that it's supposed to work like this, but could
      someone tell me the reasoning behind it? I.E. why is 3 skipped?
      >
      Because:
      >
      >alist[2]
      3
      >
      You are removing the third item, not the second.
      This is incorrect.
      You may need to remind yourself that the arg of remove is a value to be
      searched for and then removed, not an index. del alist[2] would remove
      the third item.

      You may have been confused by the OP's obfuscatory example alist = [1,
      2, 3].
      Consider this equivalent:
      | >>alist = ['foo', 'bar', 'zot']
      | >>for item in alist:
      | ... print item
      | ... if item == 'bar':
      | ... alist.remove(it em)
      | ...
      | foo
      | bar
      | >>alist
      | ['foo', 'zot']
      | >>>

      HTH,
      John

      Comment

      • Tim Williams

        #4
        Re: Removing from a List in Place

        On 5 Sep 2006 16:05:36 -0700, bayerj <bayerj@in.tum. dewrote:
        I'm going to assume that it's supposed to work like this, but could
        someone tell me the reasoning behind it? I.E. why is 3 skipped?
        >
        Because:
        >
        >alist[2]
        3
        >
        You are removing the third item, not the second.
        >
        Actually, he's removing 2 from the list, but then the length of the
        list shrinks by 1 and iteration stops.

        The example would have been better if alist = ['a','b','c'] and 'b' was removed.

        L.remove(value) -- remove first occurrence of value

        you were possibly thinking of alist.pop(2), which removes the item
        alist[2] from alist

        HTH :)


        --

        Tim Williams

        Comment

        Working...