1

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?

3
  • 2
    That's not really a 3d array. That's a 1d array with 3 elements. Commented May 16, 2012 at 20:49
  • @Falmarri is right- do you mean a list with 3 elements? Commented May 16, 2012 at 21:01
  • No I didn't mean a list with 3 elements. I was going to ask a question about 3d lists but I suppose I decided while writing the question that what I could learn about 1d lists could easily be applied to 3d lists. I fixed the title in an edit there, and changed the word array to the standard python terminology (list, not array). Commented May 17, 2012 at 0:45

2 Answers 2

4

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
Sign up to request clarification or add additional context in comments.

Comments

1

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)

1 Comment

Yes thanks for pointing that out. I'll edit and take the 3d bit out :p

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.