Decode School

Decode School - The School for Problem Solvers
Welcome to My Blog.
Need Assignment / Project Guidance (or) Training in Python?

linear search in python

Python Program to get an element and find the location of element in list, print -1 if element is not found.

Sample Input 1:

5 5 7 9 3 1 9

Sample Output 1:

2

Sample Input 2:

5 5 7 9 3 1 4

Sample Output 2:

-1

Program or Solution

					    
							
l=list(map(int,input("Enter array elements:").split(" ")))
e=int(input("Enter the element to find:"))
for i in range(0,len(l)):
    if(l[i]==e):
        print(i)
        break
else:
    print("Element not found")
    

					    
					

Program Explanation

Input: To get list of numbers seprated by space, use split(" ") method.

Split() method splits the numbers as seprate elements.

By default this methods are considered as string, since input() method returs string.

Use map() function to convert all elements as integer and store it in list.

Process: for statement takes the elements given by range(0,len(l)) method one by one as value of i, and i acts as an index of list. [0,1,2.......len(l)-1] if element is found in any list[i] then it returns the location i, else it prints "element not found".

Note : In Python, for also have else statement. if the loop does not exists by break statement, then else part will be executed.