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
Try your Solution
Strongly recommended to Solve it on your own, Don't directly go to the solution given below.
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.
Comments
Related Programs
- list input in python
- sum of list in python | without using built-in function
- Average of list in python | without using built-in function
- largest element in the list python | without using built-in function
- smallest element in the list python | without using built-in function
- Print all the numbers which are less than given key element from a given list.
- delete element in list python
- Revese the elements in list python
- Reverse the first half of list elements in python
- Reverse the second half of list elements in python
- list sort python
- list sort descending order python
- Python Program to sort half of the list elements in ascending order and next half in descending order.
- merging two lists in python
- Python Program to replace every element with the greatest element on right side
- circular list rotation in python