Python program to print the duplicate elements of an array


When it is required to print the duplicate elements of an array, the list elements are iterated over, and a nested loop is used.

Below is a demonstration of the same −

Example

 Live Demo

my_list = [1, 2, 5, 6, 8, 9, 3, 4, 8, 9, 1, 8]
print("The list is :")
print(my_list)
print("The duplicate elements in the list are : ")
for i in range(0, len(my_list)):
   for j in range(i+1, len(my_list)):
      if(my_list[i] == my_list[j]):
         print(my_list[j])

Output

The list is :
[1, 2, 5, 6, 8, 9, 3, 4, 8, 9, 1, 8]
The duplicate elements in the list are :
1
8
8
9
8

Explanation

  • A list is defined, and the elements are displayed on the console.

  • The list is iterated over, twice, and elements of the first and next concurrent position are compared.

  • If they match, that element is considered as a duplicate.

  • It is displayed on the console.

Updated on: 16-Apr-2021

1K+ Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements