object's list index

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

    object's list index

    hi,

    I need to get the index of an object in a list. I know that no two objects
    in the list are the same, but objects might evaluate as equal. for example

    list = [obj1, obj2, obj3, obj4, obj5]
    for object in list:
    objectIndex = list.index(obje ct)
    print objectIndex

    prints 0, 1, 2, 3, 2 instead of 0, 1, 2, 3, 4 because obj3 == obj5. I could loop
    through the list a second time comparing id()'s

    for object in list:
    objectIndex = 0
    for i in list:
    if id(object) == id(i):
    break
    objectIndex += 1
    print objectIndex

    but that seems like a real ugly pain. Somewhere, someplace python is keeping
    track of the current index in list, does anyone know how to access it? Or have
    any other suggestions?

  • Iain King

    #2
    Re: object's list index


    William Meyer wrote:[color=blue]
    > hi,
    >
    > I need to get the index of an object in a list. I know that no two objects
    > in the list are the same, but objects might evaluate as equal. for example
    >
    > list = [obj1, obj2, obj3, obj4, obj5]
    > for object in list:
    > objectIndex = list.index(obje ct)
    > print objectIndex
    >
    > prints 0, 1, 2, 3, 2 instead of 0, 1, 2, 3, 4 because obj3 == obj5. I could loop
    > through the list a second time comparing id()'s
    >
    > for object in list:
    > objectIndex = 0
    > for i in list:
    > if id(object) == id(i):
    > break
    > objectIndex += 1
    > print objectIndex
    >
    > but that seems like a real ugly pain. Somewhere, someplace python is keeping
    > track of the current index in list, does anyone know how to access it? Or have
    > any other suggestions?[/color]

    Um, one of us is being really really dense today :) I hope it's not
    me...
    what's wrong with:

    i = 0
    for object in list:
    objectIndex = i
    print objectIndex
    i += 1

    Iain

    Comment

    • Kent Johnson

      #3
      Re: object's list index

      William Meyer wrote:[color=blue]
      > hi,
      >
      > I need to get the index of an object in a list. I know that no two objects
      > in the list are the same, but objects might evaluate as equal. for example
      >
      > list = [obj1, obj2, obj3, obj4, obj5]
      > for object in list:
      > objectIndex = list.index(obje ct)
      > print objectIndex
      >
      > prints 0, 1, 2, 3, 2 instead of 0, 1, 2, 3, 4 because obj3 == obj5. I could loop
      > through the list a second time comparing id()'s
      >
      > for object in list:
      > objectIndex = 0
      > for i in list:
      > if id(object) == id(i):
      > break
      > objectIndex += 1
      > print objectIndex
      >
      > but that seems like a real ugly pain. Somewhere, someplace python is keeping
      > track of the current index in list, does anyone know how to access it? Or have
      > any other suggestions?
      >[/color]
      Do you actually need to find the index of an arbitrary object in the
      list or are you iterating the whole list and you need the list index
      inside the list? In either case enumerate() is your friend. To find an
      item by identity:

      def index_by_id(lst , o):
      for i, item in enumerate(lst):
      if item is o:
      return i
      raise ValueError, "%s not in list" % o

      If you just want the index available inside the loop, this replaces your
      original loop:
      for i, object in enumerate(lst):
      print i

      Kent

      Comment

      • William Meyer

        #4
        Re: object's list index

        Iain King <iainking <at> gmail.com> writes:
        [color=blue]
        > what's wrong with:
        >
        > i = 0
        > for object in list:
        > objectIndex = i
        > print objectIndex
        > i += 1
        >
        > Iain
        >[/color]

        The issues with that is you might have a complex structure below the for object
        in list: with lots of continues or breaks and you don't want to have to remember
        to change the index everytime. There is an old pep
        (http://www.python.org/peps/pep-0212.html) that describes some proposed
        solutions, but I was wondering if anything has happened since aug 2000. I might
        just use the

        for objectIndex in range(len(list) ):
        e = list[objectIndex]

        solution, though its ugly too.


        Comment

        • Sybren Stuvel

          #5
          Re: object's list index

          Iain King enlightened us with:[color=blue]
          > i = 0
          > for object in list:
          > objectIndex = i
          > print objectIndex
          > i += 1[/color]

          Why not:

          for index, object in enumerate(list) :
          print index

          Sybren
          --
          The problem with the world is stupidity. Not saying there should be a
          capital punishment for stupidity, but why don't we just take the
          safety labels off of everything and let the problem solve itself?
          Frank Zappa

          Comment

          • Iain King

            #6
            Re: object's list index


            Iain King wrote:[color=blue]
            > William Meyer wrote:[color=green]
            > > hi,
            > >
            > > I need to get the index of an object in a list. I know that no two objects
            > > in the list are the same, but objects might evaluate as equal. for example
            > >
            > > list = [obj1, obj2, obj3, obj4, obj5]
            > > for object in list:
            > > objectIndex = list.index(obje ct)
            > > print objectIndex
            > >
            > > prints 0, 1, 2, 3, 2 instead of 0, 1, 2, 3, 4 because obj3 == obj5. I could loop
            > > through the list a second time comparing id()'s
            > >
            > > for object in list:
            > > objectIndex = 0
            > > for i in list:
            > > if id(object) == id(i):
            > > break
            > > objectIndex += 1
            > > print objectIndex
            > >
            > > but that seems like a real ugly pain. Somewhere, someplace python is keeping
            > > track of the current index in list, does anyone know how to access it? Or have
            > > any other suggestions?[/color]
            >
            > Um, one of us is being really really dense today :) I hope it's not
            > me...
            > what's wrong with:
            >
            > i = 0
            > for object in list:
            > objectIndex = i
            > print objectIndex
            > i += 1
            >
            > Iain[/color]

            Reading it again, I'm thinking it probably is me...

            If you aren't looking them up sequentially then I think your second
            example is the only way. You can make it a little prettier by using
            'object is i' rather than 'id(object) == id(i)'.
            I think python only stores lists one way - i.e. each index maps to it's
            value, but no backwards trace is kept from value to index.

            Iain

            Comment

            • William Meyer

              #7
              Re: object's list index

              Kent Johnson <kent <at> kentsjohnson.co m> writes:
              [color=blue]
              > In either case enumerate() is your friend. To find an
              > item by identity:
              >
              > def index_by_id(lst , o):
              > for i, item in enumerate(lst):
              > if item is o:
              > return i
              > raise ValueError, "%s not in list" % o
              >
              > If you just want the index available inside the loop, this replaces your
              > original loop:
              > for i, object in enumerate(lst):
              > print i
              >
              > Kent[/color]

              Thanks, both you and Fredrik Lundh suggested enumerate, which seems like the
              best solution. I just need the index inside the loop, but thanks again for both
              solutions.



              Comment

              • Felipe Almeida Lessa

                #8
                Re: object's list index

                Em Sex, 2006-03-03 às 12:48 +0000, William Meyer escreveu:[color=blue]
                > Kent Johnson <kent <at> kentsjohnson.co m> writes:
                >[color=green]
                > > In either case enumerate() is your friend. To find an
                > > item by identity:
                > >
                > > def index_by_id(lst , o):
                > > for i, item in enumerate(lst):
                > > if item is o:
                > > return i
                > > raise ValueError, "%s not in list" % o
                > >
                > > If you just want the index available inside the loop, this replaces your
                > > original loop:
                > > for i, object in enumerate(lst):
                > > print i
                > >
                > > Kent[/color]
                >
                > Thanks, both you and Fredrik Lundh suggested enumerate, which seems like the
                > best solution. I just need the index inside the loop, but thanks again for both
                > solutions.[/color]

                You should *always* use enumerate. "list.index " has a high cost and
                shouldn't be used that way.

                --
                "Quem excele em empregar a força militar subjulga os exércitos dos
                outros povos sem travar batalha, toma cidades fortificadas dos outros
                povos sem as atacar e destrói os estados dos outros povos sem lutas
                prolongadas. Deve lutar sob o Céu com o propósito primordial da
                'preservação' . Desse modo suas armas não se embotarão, e os ganhos
                poderão ser preservados. Essa é a estratégia para planejar ofensivas."

                -- Sun Tzu, em "A arte da guerra"

                Comment

                • Iain King

                  #9
                  Re: object's list index


                  Iain King wrote:[color=blue]
                  > Iain King wrote:[color=green]
                  > > William Meyer wrote:[color=darkred]
                  > > > hi,
                  > > >
                  > > > I need to get the index of an object in a list. I know that no two objects
                  > > > in the list are the same, but objects might evaluate as equal. for example
                  > > >
                  > > > list = [obj1, obj2, obj3, obj4, obj5]
                  > > > for object in list:
                  > > > objectIndex = list.index(obje ct)
                  > > > print objectIndex
                  > > >
                  > > > prints 0, 1, 2, 3, 2 instead of 0, 1, 2, 3, 4 because obj3 == obj5. I could loop
                  > > > through the list a second time comparing id()'s
                  > > >
                  > > > for object in list:
                  > > > objectIndex = 0
                  > > > for i in list:
                  > > > if id(object) == id(i):
                  > > > break
                  > > > objectIndex += 1
                  > > > print objectIndex
                  > > >
                  > > > but that seems like a real ugly pain. Somewhere, someplace python is keeping
                  > > > track of the current index in list, does anyone know how to access it? Or have
                  > > > any other suggestions?[/color]
                  > >
                  > > Um, one of us is being really really dense today :) I hope it's not
                  > > me...
                  > > what's wrong with:
                  > >
                  > > i = 0
                  > > for object in list:
                  > > objectIndex = i
                  > > print objectIndex
                  > > i += 1
                  > >
                  > > Iain[/color]
                  >
                  > Reading it again, I'm thinking it probably is me...
                  >
                  > If you aren't looking them up sequentially then I think your second
                  > example is the only way. You can make it a little prettier by using
                  > 'object is i' rather than 'id(object) == id(i)'.
                  > I think python only stores lists one way - i.e. each index maps to it's
                  > value, but no backwards trace is kept from value to index.
                  >
                  > Iain[/color]

                  OTOH, if memory is not an issue, you can create a lookup yourself:

                  def createLookup(l) :
                  d = {}
                  for index in xrange(len(l)):
                  objID = id(l[index])
                  d[objID] = index
                  return d

                  lookup = createLookup(li st)
                  for i in list:
                  objectIndex = lookup[id(i)]
                  print objectIndex


                  Iain

                  Comment

                  • Steven D'Aprano

                    #10
                    Re: object's list index

                    On Fri, 03 Mar 2006 04:48:20 -0800, Iain King wrote:
                    [color=blue]
                    > I think python only stores lists one way - i.e. each index maps to it's
                    > value, but no backwards trace is kept from value to index.[/color]

                    Python lists are arrays of pointers to objects. The objects themselves
                    have no clue what lists they belong to, or what position they are in.


                    --
                    Steven.

                    Comment

                    Working...