0

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
9
  • 1
    Use arr.index(x) Commented Nov 15, 2020 at 16:39
  • @Sociopath No it do not work I tried for it Commented Nov 15, 2020 at 16:44
  • @Greg the variable should change Commented Nov 15, 2020 at 16:45
  • In [14]: [1,2,3,4,5,6,7,8,9].index(8) Out[14]: 7 Commented Nov 15, 2020 at 16:45
  • 1
    The index() method searches an element in the list and returns its position/index of fist occurrence. Commented Nov 15, 2020 at 16:53

2 Answers 2

1

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

Comments

0

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.")

1 Comment

Then, you can use any of the searching algorithms.

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.