Question
Take an element from the user and delete all the duplicates of the given element from the (array for java/list for Python) if found.
Enter the size of List:10
Enter Elements in list:
1
2
1
1
3
4
1
5
6
1
Elements in given List:
1 2 1 1 3 4 1 5 6 1
Enter the Element to be Deleted:1
List after deleting element:
2 3 4 5 6
Share code with your friends
Share on whatsapp
Share on facebook
Share on twitter
Share on telegram
Code
Java
Python
Java
import java.util.Scanner;
public class DeleteSearchedElementFromArray
{
public static void main(String[] args)
{
/* Initialize array */
int [] arr;
int n=0,i=0,j=0,k=0,item=0;
Scanner sc = new Scanner(System.in);
System.out.println("Enter size of array");
n = sc.nextInt();
arr=new int[n];
System.out.println("Enter numbers in array");
for(i=0;i< n;i++)
{
arr[i]=sc.nextInt();
}
System.out.println("Enter the item to be deleted");
item= sc.nextInt();
for(i=0;i< n;i++)
{
if(arr[i]==item)
{
k=i;
for(j=k+1;j< n;j++)
{
arr[k]=arr[j];
k++;
}
i=-1;
n=n-1;
}
}
System.out.println("array after deleting searched element");
for(i=0;i< n;i++)
{
System.out.print(arr[i]+" ");
}
}
}
Python
size=int(input("Enter the size of List:"))
li=[]
print("Enter Elements in list:")
for i in range(0,size):
print((i+1),end=": ")
li.append(int(input()))
#Print Given Elements
print("Elements in given List:")
print(li)
elementToBeDeleted=int(input("Enter the Element to be Deleted:"))
#Counting total number of elements that exists in the Given List
count=li.count(elementToBeDeleted)
if(count>0):
for i in range(0,count):
li.remove(elementToBeDeleted)
print("List after deleting element:")
print(li)
else:
print(elementToBeDeleted,"not found in given list")