Write a Python program to remove duplicate elements in an array.

Python code to remove duplicate elements from an array. below is the example to write the algorithm and program to remove the duplicate elements from an array.

How to remove duplicate elements in an array?

To implement the program is excessively simple, we need to append elements individually to another array by checking whether the element is present in the new array or not. Removing duplicate elements can be done in many ways like using a temporary list, set() function, using dictionary keys, and list comprehension.

What is the output after removing duplicate elements in an array?

Input: Array elements = [5, 10, 15, 10, 15]

Output: The elements after removing duplicate elements = [5,10,15]

Algorithm to remove duplicate elements in an array:

  • Initialize an array.
  • Create an empty array.
  • Traverse the array using for-loop and if the element is not present in the empty array, it is appended to the new array.
  • Display the new array.

Python program to remove the duplicate items in the array.

Method 1: Using the new temporary array

from array import *
arr = array('i', [])
n = int(input("enter number of elements"))
for i in range(n):
   arr.append(int(input("enter the array elements")))

print("entered array is:")
for i in range(len(arr)):
   print(arr[i])
newlist = []
for x in arr:
   if x not in newlist:
       newlist.append(x)
arr = newlist
print("Array after removing the duplicate elements =", newlist)

Output: Printing the array after removing duplicate elements

Method 2: List of Comprehension

from array import *
arr = array('i', [])
n = int(input("enter number of elements"))
for i in range(n):
   arr.append(int(input("enter the array elements")))

print("entered array is:")
for i in range(len(arr)):
   print(arr[i])
newlist = []
[newlist.append(x) for x in arr if x not in newlist]
print("Array after removing duplicate elements are", newlist)

Output: Printing the array after removing duplicate elements

Method 3: Using Dictionary keys

from array import *
arr = array('i', [])
n = int(input("enter number of elements"))
for i in range(n):
   arr.append(int(input("enter the array elements")))
print("entered array is:")
for i in range(len(arr)):
   print(arr[i])
newlist = list(dict.fromkeys(arr))
print("Array after removing duplicate numbers",newlist)

Output: Printing the array after removing duplicate elements

Method 4: Using set() function

from array import *
arr = array('i', [])
n = int(input("enter number of elements"))
for i in range(n):
   arr.append(int(input("enter the array elements")))
print("entered array is:")
for i in range(len(arr)):
   print(arr[i])
arr = list(set(arr))
print("After removing duplicate elements the array is",arr)

Output: Printing the array after removing duplicate elements