given these sublists
lst=[['a', 'b', 'c', 'd', 'e'], ['f', 'g', 'h']]
I am trying to find the location of its elements, for instance, the letter 'a' is located at 0,0 but this line
print(lst.index('a'))
instead produces the following error: ValueError: 'a' is not in list
if your list
have depth=2
, you can use this:
lst=[['a', 'b', 'c', 'd', 'e'], ['f', 'g', 'h']]
def fnd_idx(char, lst):
for x in range(len(lst)):
try:
idx = lst[x].index(char)
return [x,idx]
except ValueError:
pass
return None
Output:
>>> print(fnd_idx('a', lst))
[0, 0]
>>> print(fnd_idx('g', lst))
[1, 1]
>>> print(fnd_idx('z', lst))
None
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With