List Methods quection from a newbie

Collapse
X
 
  • Time
  • Show
Clear All
new posts
  • bhintze
    New Member
    • Jul 2008
    • 4

    List Methods quection from a newbie

    I know there is the find and rfind mathod for strings. For lists I only know the index method. is the a 'rindex' method akin to the rfind method for strings?
  • jlm699
    Contributor
    • Jul 2007
    • 314

    #2
    Not really but you can find ways around that... for instance you could use the list's reverse method, then perform your index() search and then re-reverse the list.

    Comment

    • bvdet
      Recognized Expert Specialist
      • Oct 2006
      • 2851

      #3
      You can create a function to return the last index number.
      [code=Python]def rindex(s, item):
      """
      Return the index of the last occurrence of 'item' in string/list 's'.
      Return False if 'item' is not in 's'.
      """
      i=0
      while True:
      try:
      i = s.index(item, i)
      i += 1
      except:
      return i-1
      return False[/code]Test:[code=Python]>>> rindex([1,2,3,4,5,6,5,4 ,3,2,1,2,3,4,3, 2,1], 3)
      14
      >>> [/code]

      Comment

      • bhintze
        New Member
        • Jul 2008
        • 4

        #4
        Originally posted by bvdet
        You can create a function to return the last index number.
        [code=Python]def rindex(s, item):
        """
        Return the index of the last occurrence of 'item' in string/list 's'.
        Return False if 'item' is not in 's'.
        """
        i=0
        while True:
        try:
        i = s.index(item, i)
        i += 1
        except:
        return i-1
        return False[/code]Test:[code=Python]>>> rindex([1,2,3,4,5,6,5,4 ,3,2,1,2,3,4,3, 2,1], 3)
        14
        >>> [/code]
        hhmmmm...That function won't work. I'll see what I can do. Thanks anyway

        Comment

        • jlm699
          Contributor
          • Jul 2007
          • 314

          #5
          Originally posted by bhintze
          That function won't work
          Why's that?
          Does it cause an error or are you saying that you meant something else by your question?

          Comment

          • bhintze
            New Member
            • Jul 2008
            • 4

            #6
            Originally posted by jlm699
            Why's that?
            Does it cause an error or are you saying that you meant something else by your question?
            When I try to use the function its returning false even though I know the item is in the string

            Comment

            • bhintze
              New Member
              • Jul 2008
              • 4

              #7
              Originally posted by bhintze
              When I try to use the function its returning false even though I know the item is in the string
              Somehow, it works now... Shows you how much i know. :)
              Thanks for the help.

              Comment

              Working...