IndexError: list index out of range

Collapse
X
 
  • Time
  • Show
Clear All
new posts
  • python101
    New Member
    • Sep 2007
    • 90

    IndexError: list index out of range

    My code
    [code=python]
    s=['aaaa','ccccccc c','dddd','ssss ','xxxxx','aaaa ','ssx','ssx',' cc','cc']

    for k in range(len(s)):
    st=s.count(s[k])
    if st>=2:
    print s.pop(s.index(s[k]))

    Traceback (most recent call last):
    File "C:/Python30/test.py", line 4, in <module>
    st=s.count(s[k])
    IndexError: list index out of range
    [/code]

    how can I fix the error
    IndexError: list index out of range
  • bartonc
    Recognized Expert Expert
    • Sep 2006
    • 6478

    #2
    Originally posted by python101
    My code
    [code=python]
    s=['aaaa','ccccccc c','dddd','ssss ','xxxxx','aaaa ','ssx','ssx',' cc','cc']

    for k in range(len(s)):
    st=s.count(s[k])
    if st>=2:
    print s.pop(s.index(s[k]))

    Traceback (most recent call last):
    File "C:/Python30/test.py", line 4, in <module>
    st=s.count(s[k])
    IndexError: list index out of range
    [/code]

    how can I fix the error
    IndexError: list index out of range
    That would be because of the pop(). When you shorten the list that you are indexing on you cause the error.

    By using a slice for beginning to end, you work on a copy. I threw in some other options which avoid the index all together:[CODE=python]
    >>> s=['aaaa','ccccccc c','dddd','ssss ','xxxxx','aaaa ','ss x','ssx','cc',' cc']
    >>> for item in s[:]:
    ... n = s.count(item)
    ... if n >= 2:
    ... print item
    ... s.remove(item)
    ...
    aaaa
    cc
    >>> s
    ['cccccccc', 'dddd', 'ssss', 'xxxxx', 'aaaa', 'ss x', 'ssx', 'cc']
    >>> [/CODE]
    Last edited by bartonc; Oct 5 '07, 11:02 AM.

    Comment

    • Motoma
      Recognized Expert Specialist
      • Jan 2007
      • 3236

      #3
      Originally posted by bartonc
      That would be because of the pop(). When you shorten the list that you are indexing on you cause the error.

      By using a slice for beginning to end, you work on a copy. I threw in some other options which avoid the index all together:[CODE=python]
      >>> s=['aaaa','ccccccc c','dddd','ssss ','xxxxx','aaaa ','ss x','ssx','cc',' cc']
      >>> for item in s[:]:
      ... n = s.count(item)
      ... if n >= 2:
      ... print item
      ... s.remove(item)
      ...
      aaaa
      cc
      >>> s
      ['cccccccc', 'dddd', 'ssss', 'xxxxx', 'aaaa', 'ss x', 'ssx', 'cc']
      >>> [/CODE]
      Just as a note:

      [CODE=python]
      for item in s[:]:
      [/CODE]

      is exactly the same as

      [CODE=python]
      for item in s:
      [/CODE]

      The only reason I mention this is that when learning Python, I often stumbled when I would encounter the whole array-subarray-step-bracket-thingies.

      Comment

      • KaezarRex
        New Member
        • Sep 2007
        • 52

        #4
        Originally posted by python101
        My code
        [code=python]
        s=['aaaa','ccccccc c','dddd','ssss ','xxxxx','aaaa ','ssx','ssx',' cc','cc']

        for k in range(len(s)):
        st=s.count(s[k])
        if st>=2:
        print s.pop(s.index(s[k]))

        Traceback (most recent call last):
        File "C:/Python30/test.py", line 4, in <module>
        st=s.count(s[k])
        IndexError: list index out of range
        [/code]

        how can I fix the error
        IndexError: list index out of range
        Here is a way to get rid of duplicate items in a list that probably isn't good form, but I thought it was interesting. I put everything in a dictionary, which can't have duplicate keys, and then retrieved the list of keys.
        [CODE=python]>>> s=['aaaa','ccccccc c','dddd','ssss ','xxxxx','aaaa ','ssx','ssx',' cc','cc']
        >>> d=dict([(s[i], i) for i in range(len(s))])
        >>> s=d.keys()
        >>> print s
        ['cccccccc', 'ssss', 'ssx', 'cc', 'aaaa', 'dddd', 'xxxxx'][/CODE]
        If you were using an ordered list this way wont work because the dictionary keys are in an unordered list.

        Comment

        • KaezarRex
          New Member
          • Sep 2007
          • 52

          #5
          Originally posted by Motoma
          Just as a note:

          [CODE=python]
          for item in s[:]:
          [/CODE]

          is exactly the same as

          [CODE=python]
          for item in s:
          [/CODE]

          The only reason I mention this is that when learning Python, I often stumbled when I would encounter the whole array-subarray-step-bracket-thingies.
          It's actually different (and very useful) because "s[:]" creates a whole new list (a deep copy) to iterate through, instead of iterating over "s" itself. That way the loop can modify "s" without throwing an error.

          Comment

          • Motoma
            Recognized Expert Specialist
            • Jan 2007
            • 3236

            #6
            Originally posted by KaezarRex
            It's actually different (and very useful) because "s[:]" creates a whole new list (a deep copy) to iterate through, instead of iterating over "s" itself. That way the loop can modify "s" without throwing an error.
            Oh man...Owned.

            You learn something new every day. Thanks for the lesson KaesarRex!

            Comment

            • bartonc
              Recognized Expert Expert
              • Sep 2006
              • 6478

              #7
              Originally posted by KaezarRex
              It's actually different (and very useful) because "s[:]" creates a whole new list (a deep copy) to iterate through, instead of iterating over "s" itself. That way the loop can modify "s" without throwing an error.
              Actually, Motoma has a point. When working with arrays, the elements are passed by reference (even in a slice). Lists and arrays are not interchangeable that way!

              Comment

              • KaezarRex
                New Member
                • Sep 2007
                • 52

                #8
                Originally posted by bartonc
                Actually, Motoma has a point. When working with arrays, the elements are passed by reference (even in a slice). Lists and arrays are not interchangeable that way!
                Looks like I've learned something too. Thanks for the clarification.

                Comment

                Working...