A. N. Other
A. N. Other

Reputation: 407

How to find the index of the first instance of a list (in a list) containing the wanted value (in Python)?

I have a list of tuples that looks like the following

list_of_list = [(0,1,2), (0,1), (0,1,3,4), (0,1,2,3,4)]

I want to find the index for the first time I have a particular integer. For example, I want to find the first time 3 exists, and want it to return the index 2. I also want it to return None if it cannot find anything. I currently have the following code

def find_index_of_solution(list_of_list, value_I_am_searching_for):
  for idx, list_item in enumerate(list_of_list):
    if value_I_am_searching_for in list_item:
      return idx
  return None

Is there a better way of doing this? Thank you!

Upvotes: 0

Views: 79

Answers (2)

jwdasdk
jwdasdk

Reputation: 183

Yours :

%%timeit
list_of_list = [(0,1,2), (0,1), (0,1,3,4), (0,1,2,3,4)]


def findIdx(list_of_list, value_I_am_searching_for):
    for idx, list_item in enumerate(list_of_list):
        if value_I_am_searching_for in list_item:
          return idx
    return None


findIdx(list_of_list, 3)


1000000 loops, best of 3: 1.18 µs per loop

Blue_note's :

%%timeit
list_of_list = [(0,1,2), (0,1), (0,1,3,4), (0,1,2,3,4)]
my_value = 3
try:
    return next(index for index, lst in enumerate(list_of_list) if my_value in lst)
except StopIteration:
    return None

1 loop, best of 3: 2 s per loop

Another one :

%%timeit
list_of_list = [(0,1,2), (0,1), (0,1,3,4), (0,1,2,3,4)]


def findIdx(lst, i):
    return [l.index(i) if i in l else 'None' for l in lst ]


findIdx(list_of_list, 3)

100000 loops, best of 3: 2 µs per loop

My opinion, stick with what you have for now..

Edit : I missed this ...

For example, I want to find the first time 3 exists, and want it to return the index 2.

nvm.

Upvotes: 1

blue note
blue note

Reputation: 29071

try:
    return next(index for index, lst in enumerate(list_of_list) if my_value in lst)
except StopIteration:
    return None

Inside the parentheses, is a generator expression. next returns the first element. enumerate is used to iterate over both index and value of an iterable. Finally, using an exception is preferred to checking in python, both as style and performance-wise

Upvotes: 1

Related Questions