using the 'in' keyword i can find if an element is in an array:
a=[1,2,3]
if 1 in a:
print "1 present in a"
is there a way to return the index of where 'in' found that element?
using the 'in' keyword i can find if an element is in an array:
a=[1,2,3]
if 1 in a:
print "1 present in a"
is there a way to return the index of where 'in' found that element?
1-d list:
a=[1,2,3]
def indd(val):
try:
ind=a.index(val)
return ind,val
except:
return 'not found'
print(indd(1))
print(indd(5))
(0,1)
not found
for a 3-d list the function function will return a tuple of the x,y,z , if the number is repeated inside the 3d list then it'll return the lowest index :
def ind_3d(lis,val):
ind=[(j,i,k) for j,x in enumerate(lis) for i,y in enumerate(x) for k,z in enumerate(y) if z==val]
if len(ind)==0:
return 'not found'
else:
return ind[0]
a=[[[1,2,3],[4,5,6],[7,8,9]],[[11,12,13],[14,15,16],[17,18,19]]]
print(ind_3d(a,11))
print(ind_3d(a,5))
print(ind_3d(a,25))
output:
(1, 0, 0)
(0, 1, 1)
not found
Use a.index(1) to get the position of 1 in the list if you know it exists for sure. Otherwise use a try/catch block.
Also, they're called "lists" in Python :) The more accurate you are with terminology the easier it is to keep track later of how they're implemented and what functions they support.
EDIT: For a multi-dimensional list (i.e. list of lists in case of 2-D), you'll have to iterate over the top n-1 levels, where n is the dimensionality. For 2-D, assuming you're searching for 1, something like this will work:
for idx, val in enumerate(a):
if 1 in val:
return idx, val.index(1)