-1
def main():
  testList = [3, 1, 8, 1, 5, 2, 21, 13]
  print("searching for 5 in", testList,"...")
  searchResult1 = linearSearch(testList, 5)
  print(searchResult1)


def linearSearch(aList, target):
  for item in aList:
    if item == target:
      return True

  return False



main()

Instead of returning true if the value is in the list, how can I return the position of that value?

  • what happen when you encounter duplicates target values, what you want then ? `aList.index(target)` works if you want first occurence index – sahasrara62 Dec 13 '20 at 21:37
  • Does this answer your question? [Finding the index of an item in a list](https://stackoverflow.com/questions/176918/finding-the-index-of-an-item-in-a-list) – wjandrea Dec 13 '20 at 21:43
  • Wait, why did you edit the code? The question doesn't make any sense anymore. – wjandrea Dec 13 '20 at 22:05

2 Answers2

0

Use list.index():

>>> testList = [3, 1, 8, 1, 5, 2, 21, 13]
>>> testList.index(5)
4
>>> testList.index(16)
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
ValueError: 16 is not in list

By the way, for checking membership, use in:

>>> 5 in testList
True
>>> 16 in testList
False

Docs: Common Sequence Operations

wjandrea
  • 28,235
  • 9
  • 60
  • 81
0

If you want to keep your code entirely, you can use enumerate for getting index position.

def linearSearch(aList, target):
  for ix, item in enumerate(aList):
    if item == target:
      return ix
  return False 
Ismail Durmaz
  • 2,521
  • 1
  • 6
  • 19
  • Returning `False` is questionable because `False == 0`. – wjandrea Dec 13 '20 at 22:01
  • @ivanlin2020 wants to get rid of the "True" response. There is no comment about "False" response. – Ismail Durmaz Dec 13 '20 at 22:03
  • I know, I'm saying that you should return something other than `False` if the value is not found, because `0` is a possible index, and `False == 0`. For example, `linearSearch(testList, 3)` -> `0`; `linearSearch(testList, 16)` -> `False`. As a fix, you could use `-1`, like `str.find()`. – wjandrea Dec 13 '20 at 22:12