Search a number in an array using Python

Hey Pythoneers,
In this tutorial, we will see how to search for a number in an array. In Python, an array can contain different types of values such as string, number etc. But here, we will see an example of an integer array.

For using array in our program we need to import the array module:-

from array import *

We also need to use the append function to store numerous values in the array. Suppose, we need to enter the numbers in an array ‘a’. Then, you should use the append function.

a.append(x)

Let’s see the full code to search a number from an array:

from array import *
a=array('i', [])
n=int(input("Enter the length of the array: "))
for i in range(n):
    x=int(input("Enter a value: "))
    a.append(x)
print(a)

s=int(input("Enter the number to be searched: "))
c=0
for j in range(n):
    if a[j] == s:
        print("FOUND!")
        c+= 1
        break

if(c!=1):
    print("NOT FOUND!")

Suppose, you enter the length of the array as ‘5’. Then, you have to enter the values in the array. After entering the values the array is printed and a prompt message is shown asking you the number to be searched. The above program will produce the following output:-

Enter the length of the array: 5
Enter the value: 3
Enter the value: 11
Enter the value: 7
Enter the value: 55
Enter the value: 71
array('i', [3, 11, 7, 55, 71])
Enter the number to be searched:11
FOUND!

So, here it is. A very simple program in Python to search for a number.

Also read,

A simple Candy Machine in Python

The simplest GUI using Python

Thank You!

Leave a Reply

Your email address will not be published. Required fields are marked *