Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Python: Return 2 ints for index in 2D lists given item

I've been tinkering in python this week and I got stuck on something.
If I had a 2D list like this:

myList = [[1,2],[3,4],[5,6]]

and I did this

>>>myList.index([3,4])

it would return

1

However, I want the index of something in side one of the lists, like this

    >>>myList.index(3)

and it would return

1, 0

Is there anything that can do this?

Cheers

like image 663
Sam Jarman Avatar asked Apr 25 '11 05:04

Sam Jarman


1 Answers

Try this:

def index_2d(myList, v):
    for i, x in enumerate(myList):
        if v in x:
            return (i, x.index(v))

Usage:

>>> index_2d(myList, 3)
(1, 0)
like image 186
Mark Byers Avatar answered Oct 12 '22 11:10

Mark Byers