Python program to print the duplicate elements of an array [4 Methods]

Do you want to get all the duplicate values of an array? In this NumPy article, I will explain some Python program to print the duplicate elements of an array using different methods.

To print the duplicate elements of an array in Python, various methods like using a nested for loop allow for manual comparison of each element with others to find duplicates. The np.unique function with return_counts in NumPy efficiently identifies duplicates by counting occurrences. Boolean indexing compares sorted elements to find repeating values and collections.Counter from Python’s standard library tallies elements to easily spot duplicates.

Python program to print the duplicate elements of an array

We can create a Python program to print the duplicate elements of an array in four different ways.

  1. Nested for loop
  2. Using np.unique with return_counts
  3. Using Boolean Indexing
  4. Using collections.Counter

Let’s see them one by one using some illustrative examples:

1. Duplicate elements in an array in Python using nested for loop

In the nested for loop method for identifying duplicates, we iterate over each element of the array using an outer loop. For each element, an inner loop runs to compare this element with all other elements in the array. When a match is found (indicating a duplicate), it is recorded.

Python program to print the duplicate elements of an array using nested for loop:

import numpy as np

cities = np.array(['New York', 'Chicago', 'Los Angeles', 'New York', 'Houston', 'Chicago', 'Miami'])
duplicates = set()
for i in range(len(cities)):
    for j in range(i + 1, len(cities)):
        if cities[i] == cities[j]:
            duplicates.add(cities[i])

print("Duplicate Cities:", duplicates)

Output:

Duplicate Cities: {'New York', 'Chicago'}

Following the execution of the code within the Pycharm editor, a screenshot of the outcome is displayed below.

Duplicate elements in an array in Python

2. How to find duplicates from a list in Python using np.unique with return_counts

This method leverages np.unique function to find unique elements and their occurrence counts in an array in Python. It then filters out elements with counts greater than one, identifying these as duplicates.

Python program to print the duplicate elements of an array using np.unique with return_counts parameter:

import numpy as np

state_codes = np.array(['CA', 'NY', 'TX', 'FL', 'CA', 'NY', 'WA', 'TX', 'TX'])

unique_states, counts = np.unique(state_codes, return_counts=True)
duplicates = unique_states[counts > 1]
print("Duplicate State Codes:", duplicates)

Output:

Duplicate State Codes: ['CA' 'NY' 'TX']

Following the execution of the code in PyCharm, the resulting output is captured in the screenshot displayed below.

Python program to print the duplicate elements of an array

3. Print Duplicate Elements in Array Using Boolean Indexing

In this approach, the array is first sorted, and then adjacent elements are compared using boolean indexing. This comparison helps identify and extract duplicate values by checking where consecutive elements are equal.

Python program to print the duplicate elements of an array using boolean indexing:

import numpy as np

zip_codes = np.array([90210, 10001, 73301, 90210, 33101, 10001])
sorted_zip = np.sort(zip_codes)
duplicates_bool = sorted_zip[1:] == sorted_zip[:-1]
duplicates = np.unique(sorted_zip[:-1][duplicates_bool])
print("Duplicate ZIP Codes:", duplicates)

Output:

Duplicate ZIP Codes: [10001 90210]

Below is a screenshot depicting the output, captured after the code was run in the PyCharm editor.

print duplicate elements of an array in Python

4. Python Program to Find Duplicate Elements of an Array Using collections.Counter

This method uses Python’s Counter class from the collections module. It counts the occurrences of each element in the array. The duplicates are then identified as elements with a count greater than one.

Python program to print the duplicate elements of an array using collections.Counter() function.

import numpy as np
from collections import Counter

cities = np.array(['New York', 'Los Angeles', 'Chicago', 'Houston', 'Phoenix', 'Chicago', 'Houston'])
city_counts = Counter(cities)
duplicates = [city for city, count in city_counts.items() if count > 1]
print("Duplicate Cities:", duplicates)

Output:

Duplicate Cities: ['Chicago', 'Houston']

The screenshot provided below showcases the output generated after running the code in the PyCharm editor.

Python Program To Print The Duplicate Elements In An Array

Conclusion

Here, I have explained four distinct methods to write a Python program to print the duplicate elements of an array: utilizing a nested for loop for element-by-element comparison, employing np.unique with return_counts parameter for efficient counting in NumPy, leveraging Boolean indexing to identify duplicates in sorted arrays, and using collections.Counter for straightforward tallying in Python’s standard library.

Each method caters to different scenarios and showcases the versatility of Python in handling array data.

You may also like to read: