I have a list that looks like this:
lst = [['Apple Pie', 'Carrot Cake'], ['Steak', 'Chicken']]
I would like to find the index of the list that contains the word ' Carrot', so in this case, the output should be 0
I have tried to make a function
def find_index(l, c):
for i, v in enumerate(l):
if c in v:
return i
res = find_index(lst, 'Carrot')
but this does not work since it looks for items in the list.
Can anyone help me to retreive the index of the list that contains 'Carrot'?
Thanks!
Edit: I received multiple answers for this question, and they all worked. so I decided to time them and accept the fastest one as the answer. here are the results:
import timeit
lst = [['Apple Pie', 'Carrot Cake'], ['Steak', 'Chicken']]
def find_index(l,c):
for i,v in enumerate(l):
for j in v:
if c in j:
return i
print(timeit.timeit('%s'%(find_index(lst,'Carrot Cake'))))
def find_index(l, c):
for i, v in enumerate(l):
if any(c in x for x in v):
return i
print(timeit.timeit('%s'%(find_index(lst,'Carrot Cake'))))
def function(list_contains,word_to_know):
for x in list_contains:
for y in x:
if word_to_know in y:
return list_contains.index(x)
print(timeit.timeit('%s'%(function(lst,'Carrot Cake'))))
def index_of_substr(l, substr):
for i, inner_list in enumerate(l):
for text in inner_list:
if substr in text:
return i
return -1
print(timeit.timeit('%s'%(function(lst,'Carrot Cake'))))
0.005458000000000001
0.005462599999999998
0.005485600000000004
0.0054621000000000045
any()function help?