linear search in python

Description

Python Program to get an element and find the location of element in list, print -1 if element is not found.
Input:
5
5 7 9 3 1
9
Output:
2
Input:
5
5 7 9 3 1
4
Output:
-1

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")
    

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.




Interesting Pattern Programs: for more Patterns

Input:
5
Output:
*
**
***
****
*****
****
***
**
*Solution
Input:
5
Output:
    *
   ***
  *****
 *******
*********
 *******
  *****
   ***
    *Solution
Input:
5
Output:
*        *
**      **
***    ***
****  ****
**********Solution
Input:
5
Output:
*       *
**     **
***   ***
**** ****
*********Solution
Input:
5
Output:
*       *
**     **
***   ***
**** ****
*********
**** ****
***   ***
**     **
*       *Solution
Input:
5
Output:
*********
 *******
  *****
   ***
    *
   ***
  *****
 *******
*********Solution