Whizkid95
Whizkid95

Reputation: 271

Find index of a given number in a list python3

I've written a program that gives me the index of a given integer of my choosing (x) in a list. Also, when a given integer isn't in the list, I want the program to give me the output -1 (or None).

list = [7,13,6,1]
x = 5
for i,j in enumerate(list):
    if j==x:
            print(i)
    else:
            print(-1)

However. If I use this on for instance the list given above, the output will be

-1
-1
-1
-1

Where I only want -1. Any thoughts? Update I also want the program to give me only the index of the first integer it finds, whereas it now gives me the index of all the numbers, equal to x, which it finds in the list

Upvotes: 1

Views: 3695

Answers (2)

miradulo
miradulo

Reputation: 29690

You can use index, which returns the first index value if it exists and if not raises a ValueError, and a try-except clause to handle the error:

l = [7,13,6,1]
x = 5

try:
    print(l.index(x))
except ValueError:
    print(-1)

Upvotes: 3

Tadhg McDonald-Jensen
Tadhg McDonald-Jensen

Reputation: 21453

the else clause will happen on each run through the loop, if you unindent it to be on the for loop instead it will only run if the for loop does not break, and if you do find one that matches then you should break out so that it only shows the first occurence:

for i,j in enumerate(list):
    if j==x:
        print(i)
        break
else:
    print(-1)

Upvotes: 2

Related Questions