1

I want to define a function, to find out the index of a list which satisfies some condition. But it always have some error:

TypeError: 'int' object is not iterable

Below is my code

def find_index(x,*arr):
    for i in len(arr):
        if abs(i-x) < 1e-5:
            j = arr.index(i)
            return j

How do I specify arr is a list or numpy array? (Sorry, I do not know how to format the code in this editor)

Thanks a lot.

0

3 Answers 3

4

The (first) problem is for i in len(arr). len(arr) returns an integer which isn't iterable. You might be tempted to use a range(len(arr)), but don't give in. There are better options! We can keep track of the index of the value as we iterate. Generally, this function would probably look something like:

def find_index(x, arr):
    for i, val in enumerate(arr):
        if abs(val - x) < 1.e-5:
            return i

Now you can call this on any iterable. e.g.:

find_index(5, [1, 2, 3, 5, 60])  # passing a list
find_index(5, (0, 5+1e-6, 10))  # passing a tuple
Sign up to request clarification or add additional context in comments.

2 Comments

Just to clarify the use of enumerate: arr.index(i) is wasteful if you just want to know the index of the already found element.
Thank you very much. Learn a lot from you.
0

I think you would want to replace

for i in len(arr)

with:

for i in range(len(arr))

Comments

0

You can Try to like :

   l=len(arr)
   for i in range(l)

i returns is integer value .integer value not iterable.

Comments

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.