Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Python: list.index fails to find existing element

Tags:

python

list

Can someone explain to me how the funcion list.index() functions? I have the following code:

def getPos(self,tile):
        print self.tiles[5][5]
        print tile
        try:
           myIndex = self.tiles.index(tile)
           #some code
        except:
           print "exception raised"
           #some code

The result:

<Tile.Tile instance at 0x36BCEB8>
<Tile.Tile instance at 0x36BCEB8>
exception raised

Do you have an idea why list.index() returns an exception although the tile variable is a reference to an element of tiles[][] ? Thanks a lot.

ps: btw I'm passing tiles[5][5] in this specific case

like image 662
gramm Avatar asked Nov 27 '25 13:11

gramm


2 Answers

self.tiles appears to be a sequence (e.g. list or tuple) of sequences. Elements of self.tiles are sequences, not tiles.

self.tiles.index(tile) tries to find a sequence which equals tile, and fails.

Try instead:

def getPos(self,tile):
    for i,row in enumerate(self.tiles):
        for j,elt in enumerate(row):
            if tile == elt:
                return (i,j)
    raise ValueError('no tile found')
like image 113
unutbu Avatar answered Nov 29 '25 04:11

unutbu


While the element does exist, it is not directly a member of tiles:

  • tiles is a two-dimensional list (a list of lists).
  • tiles[5] is a list of Tiles.
  • tiles[5][5] is a single Tile.

Python does not recursively descend into a multidimensional list to find the element you're looking for. Therefore tiles.index(tile) fails; tiles[5].index(tile) would work.

To illustrate:

>>> l = [[1,2], [3,4]]
>>> l.index(4)
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
ValueError: 4 is not in list
>>> l[1].index(4)
1
like image 36
Tim Pietzcker Avatar answered Nov 29 '25 03:11

Tim Pietzcker



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!