[SOLVED] Finding the index of an item in a list of lists

Issue

This Content is from Stack Overflow. Question asked by donto

I am trying to implement next(i for i,v in enumerate(l) if 12 in v) like in this post, but when I replace 12 with variable myvar, it throws error NameError: name 'myvar' is not defined. The code is:

myvar=12
next(i for i,v in enumerate(l) if myvar in v)

How to solve this? Thank you.



Solution

Just use enumerate:

l = [[1,2,3,4],[5,6,7,8,9,10],[11,12,13]]

# e.g.: find the index of the list containing 12
# This returns the first match (i.e. using index 0), if you want all matches
# simply remove the `[0]`
print [i for i, lst in enumerate(l) if 12 in lst][0] 

This outputs:

[2]

Edit:

@hlt’s comment suggests using the following for more efficient behavior:

next(i for i,v in enumerate(l) if 12 in v)


This Question was asked in StackOverflow by Peaser and Answered by jrd1 It is licensed under the terms of CC BY-SA 2.5. - CC BY-SA 3.0. - CC BY-SA 4.0.

people found this article helpful. What about you?