p = [['a','b','c'],['x','y','z']]
How can I get the list index containing the string(char) 'a'?
'a' in list doesn't work, or at least I can't figure it out.
use in but in the sublists, not in the global list of lists. Combined with enumerate to get the index of the matching list(s)
p = [['a','b','c'],['x','y','z']]
idx = [i for i,sublist in enumerate(p) if 'a' in sublist]
that gives you a list of indexes. Here we have only one element:
>>> idx
[0]
You can use the same technique to compute the index of a in the sublist BTW (with idx = [i for i,sublist in enumerate(p) if 'a' in sublist])
To get a sole value or None, just iterate once on a generator comprehension:
idx = next((i for i,sublist in enumerate(p) if 'a' in sublist),None)
If you set the maximum nesting depth to 2 you can use the following code to get both indices.
p = [['a','b','c'],['x','y','z']]
def get_indices(p, search_for='a'):
return [(i, sublist.index(search_for)) for i,sublist in enumerate(p) if search_for in sublist]
print('a', get_indices(p, search_for='a'))
print('b', get_indices(p, search_for='b'))
print('c', get_indices(p, search_for='c'))
print('x', get_indices(p, search_for='x'))
print('y', get_indices(p, search_for='y'))
print('z', get_indices(p, search_for='z'))
print('k', get_indices(p, search_for='k'))
output:
a [(0, 0)]
b [(0, 1)]
c [(0, 2)]
x [(1, 0)]
y [(1, 1)]
z [(1, 2)]
k []
print([i for i, v in enumerate(p) if "a" in v])?