Open In App

Python – Check if list contains all unique elements

Last Updated : 19 Dec, 2024
Comments
Improve
Suggest changes
Like Article
Like
Report

To check if a list contains all unique elements in Python, we can compare the length of the list with the length of a set created from the list. A set automatically removes duplicates, so if the lengths match, the list contains all unique elements. Python provides several ways to check if all elements in a list are unique, Let’s explore the best methods to achieve this.

Using set()

Sets in Python inherently store unique values. By converting the list to a set, we can compare its length with the original list.

Python
# Check if a list contains all unique elements
a = [1, 2, 3, 4, 5]

# Compare lengths of the list and the set
b = len(a) == len(set(a))

print(b) 

Output
True

Explanation:

  • The set(a) removes duplicates automatically.
  • If the lengths of the set and list are equal, all elements in the list are unique.

Let’s explore some more methods to check if list contains all unique elements.

Using a Loop with a Set

We can iterate through the list and check for duplicates using a set to keep track of seen elements.

Python
a = [1, 2, 3]
seen = set()

# Check for duplicates
unique = True
for x in a:
    if x in seen:
        unique = False
        break
    seen.add(x)

print(unique) 

Output
True

Explanation:

  • A set keeps track of elements we’ve already seen.
  • If an element is found in the set during iteration, the list contains duplicates.

Using the collections.Counter

The Counter class from collections can count the occurrences of each element in the list.

Python
from collections import Counter

a = [1, 2, 3, 4, 5]
counts = Counter(a)

# Check if all elements appear only once
unique = all(value == 1 for value in counts.values())

print(unique) 

Output
True

Explanation:

  • Counter(a) creates a dictionary where keys are elements and values are their counts.
  • If all counts are 1, the list has all unique elements.

Using Nested Loops

This is the brute-force approach which compares every element with every other element.

Python
a = [1, 2, 3, 4, 5]

x = all(a[i] != a[j] for i in range(len(a)) for j in range(i + 1, len(a)))

print(x)  

Output
True

Explanation:



Practice Tags :

Similar Reads