ByteBoard Notes Notes

Input a list or tuple of elements and search for a given element

Computer Science XI · Experiment 21 of 27 · Python

★ CBSE suggested11-CSPython programs
Expt. No.21
Page No.42

Linear search in a list and tuple

Aim

To write a Python program that searches for an element in a list using linear search, and in a tuple using the in operator and index().

Concepts used

Algorithm

  1. Input the elements into a list and the element to search for.
  2. Compare the element with each item in turn.
  3. If a match is found, display its position and stop.
  4. If the loop ends with no match, display "not found".
  5. Repeat the search on a tuple using in and index().

Program

# Linear search in a list, and search in a tuple nums = []n = int(input("How many elements? "))for i in range(n):    nums.append(int(input("Enter element: ")))key = int(input("Enter the element to search: ")) found = Falsefor i in range(len(nums)):    if nums[i] == key:        print(key, "found in the list at position", i + 1)        found = True        breakif not found:    print(key, "is not in the list") t = tuple(nums)if key in t:    print("In the tuple it is at index", t.index(key))else:    print("It is not in the tuple either")

A marked line continues the line above it. In your file, write it on the same line.

Output

Run 1
$ python linear_search.py
How many elements? 5 Enter element: 14 Enter element: 8 Enter element: 23 Enter element: 42 Enter element: 16 Enter the element to search: 23 23 found in the list at position 3 In the tuple it is at index 2
Run 2
$ python linear_search.py
How many elements? 5 Enter element: 14 Enter element: 8 Enter element: 23 Enter element: 42 Enter element: 16 Enter the element to search: 50 50 is not in the list It is not in the tuple either

✓ Printed by running this program, not typed by hand.

Result

23 was found at position 3 of the list (index 2 of the tuple). 50 was not found in either.

Viva voce: what the examiner may ask

01What is linear search?

Checking the items one by one from the start until the element is found or the list ends.

02What is the difference between position and index here?

The index starts at 0; the position shown to the user starts at 1, so position = index + 1.

03What happens if t.index(key) is called for a value that is not in the tuple?

It raises ValueError, which is why in is checked first.

Variations for the lab test

  1. Display every position where the element occurs, not just the first.
  2. Count the comparisons made before the element was found.
  3. Search for a name in a list of names.
! Common mistake Printing "not found" inside the loop's else branch prints it once for every item that does not match.
Back to the 11-CS index