3

I just started python and tried to create a simple linear search program

list1=[4,2,7,5,12,54,21,64,12,32]
x=int(input("Please enter a number to search for :  "))
for i in list1:
    if x==i:
        print("We have found",x,"and it is located at index number",list1.index(i))

My problem is if I change the list to [4,2,7,5,12,54,21,64,12,2,32] it doesn't output both locations of the 2 value.

Any help is much appreciated.

slamballais
  • 3,161
  • 3
  • 18
  • 29
  • check [here](https://stackoverflow.com/questions/176918/finding-the-index-of-an-item-in-a-list) – m.i.cosacak May 19 '21 at 09:48
  • Did you try to debug your program? e.g. check what's `x` and `i` in each step of the loop. That would take you into the right direction. – Bizhan May 19 '21 at 16:19

1 Answers1

4

This is because your are using list1.index(i)

list.index() only returns the first occurrence of the matching element only. So even when your loop is finding the second occurence of any number, this function will return the first occurence's index only.

Since you are printing the index of the searched element, you can use enumerate for that:

>>> list1 = [4,2,7,5,12,54,21,64,12,2,32]
>>> x=int(input("Please enter a number to search for :  "))
Please enter a number to search for :  2
>>> 
>>> for idx, i in enumerate(list1):
...     if x==i:
...         print("We have found",x,"and it is located at index number",idx)
... 
We have found 2 and it is located at index number 1
We have found 2 and it is located at index number 9

enumerate iterates over your list1, and returns a tuple value: idx, i in each iteration, where i is the number from your list1, and idx is its index.

Ank
  • 1,704
  • 9
  • 14