Reputation: 167
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
Upvotes: 5
Views: 551
Reputation: 31
You can use list comprehension:
>>> lst=[['a', 'b', 'a', 'd', 'a'], ['f', 'g', 'a'], ['a','a','b']]
>>> [(i,j) for i in range(len(lst)) for j in range(len(lst[i])) if lst[i][j]=='a']
[(0, 0), (0, 2), (0, 4), (1, 2), (2, 0), (2, 1)]
Upvotes: 0
Reputation: 24049
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
Upvotes: 2
Reputation: 416
If 'a' can appear in multiple sublists, and you want the index in each sublist:
def GetIndexes(lst, val):
pos = []
for sublist in lst:
try:
idx = sublist.index(val)
pos.append(idx)
except:
pos.append(None)
return pos
In your example : [0, None]
Meaning: In sublist 0, the first 'a' is at the index 0. In sublist 1, there is no 'a'.
Upvotes: 0
Reputation: 36
lst=[['a', 'b', 'c', 'd', 'c'], ['f', 'g', 'h']]
searchvalue = 'f'
counter = 0
for index in lst:
if searchvalue in index:
print(counter, index.index(searchvalue))
counter+=1
Upvotes: 0
Reputation: 144
you can do this with numpy, the benefit is you don't have to hardcode anything for the size of nested lists. you can have hundreds or 3 and this will work!
lst=[['a', 'b', 'c', 'd', 'e'], ['f', 'g', 'h']]
arr = np.array(lst, dtype=object)
for x in arr:
try:
print (x.index('a'), x)
except:
pass
Upvotes: -1
Reputation: 15364
Try this function (just one line of code!):
def idx(lst, el):
return next(((i, sublst.index(el))
for i, sublst in enumerate(lst)
if el in sublst),
None)
So for example:
>>> idx(lst, 'a')
(0, 0)
>>> idx(lst, 'c')
(0, 2)
Upvotes: 0