Reputation: 84
I want to find the index of a variable in a number list.
My code is this:
arr = [1,2,3,4,5,6,7,8,9]
x = 8
a=x
while x == a:
b = len(arr)//2
if arr[b]==x:
# find the index of x variable
Upvotes: 0
Views: 895
Reputation: 180
The same problem achieved by the linear search algorithm:
arr = [1,2,3,4,5,6,7,8,9]
x=8
flag = False
index = None
for i in range(len(arr)):
if arr[i] == x:
flag = True
index = i
if not flag:
print("Number is not present in list.")
else:
print(index)
Upvotes: 1
Reputation: 180
If you want to find the index of a variable in a number list, you can directly use the built-in method of python that is index
. It gives ValueError
if the number is not present in the list.
try:
arr = [1,2,3,4,5,6,7,8,9]
x=8
print(arr.index(x))
except ValueError:
print("Number is not present in list.")
Upvotes: 0