3

I have a list:

mylist = [[0, [0]], [2, [1]], [3, [4]], [4, [1, 4]]]

I want to get the index of the element of the outer list given the element.

I have tried this, but this only fetches me the outer elements of the list.

get_index = [outer for outer, inner in mylist]

I want something like this:

Input: 2
Output: 1

Input: 4
Output: 3
yatu
  • 80,714
  • 11
  • 64
  • 111
AlyssaAlex
  • 636
  • 1
  • 8
  • 24
  • Possible duplicate of [Finding the index of elements based on a condition using python list comprehension](https://stackoverflow.com/questions/7270321/finding-the-index-of-elements-based-on-a-condition-using-python-list-comprehensi) – mkrieger1 May 21 '19 at 14:38
  • The condition here being `element[0] == target`. – mkrieger1 May 21 '19 at 14:39

3 Answers3

3

You could use a dictionary comprehension with enumerate to easily look up the index from the first values:

d = {i[0]:ix for ix, i in enumerate(mylist)}
# {0: 0, 2: 1, 3: 2, 4: 3}

d[2]
# 1

d[4]
# 3
yatu
  • 80,714
  • 11
  • 64
  • 111
0

A function matching the desired input/output behavior:

def loc( x, ml ):
    return [a for a,b in ml].index(x)
Scott Hunter
  • 46,905
  • 10
  • 55
  • 92
0

You can also create a function to which you pass an Input and get the corresponding index as output

def get_index(inp):
    idx = [i for i, j in enumerate(mylist) if inp==j[0]]
    return idx[0]

inp = 2
get_index(inp)
# 1

inp = 4
get_index(inp)
# 3
Sheldore
  • 35,129
  • 6
  • 43
  • 58