Use enumerate with for loop to Find the index of an element in the list of lists in Python. You can easily access the index and value with the use of by looping through the list using enumerate
Find the index of an element in the list of lists Python example
A simple example code finds 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]
.
l = [[1, 2, 3, 4], [5, 6, 7, 8, 9, 10], [11, 12, 13]]
res = [i for i, lst in enumerate(l) if 12 in lst][0]
print("index of an 12 in the list of lists ", res)
Output:
Get single item by indexing the sub list
CATEGORIES = [
[1, 'New', 'Sub-Issue', '', 1],
[2, 'Replace', 'Sub-Issue', '', 5],
[3, 'Move', 'Sub-Issue', '', 7],
]
# return single item by indexing the sub list
res = next(c for c in CATEGORIES if c[0] == 2)
print(res)
Output: [2, ‘Replace’, ‘Sub-Issue’, ”, 5]
Returns a list of tuples containing (outer list index, inner list index)
from cffi.backend_ctypes import xrange
l = [['apple', 'banana', 'kiwi'], ['chair', 'table', 'spoon']]
def findItem(list1, item):
return [(ind, list1[ind].index(item)) for ind in xrange(len(list1)) if item in list1[ind]]
print(findItem(l, 'apple'))
print(findItem(l, 'spoon'))
Output:
[(0, 0)]
[(1, 2)]
Do comment if you have any doubts or suggestions on this Python list topic.
Note: IDE: PyCharm 2021.3.3 (Community Edition)
Windows 10
Python 3.10.1
All Python Examples are in Python 3, so Maybe its different from python 2 or upgraded versions.