How to check a list contains only unique elements or not in the Python

In this tutorial, we will see the Python program to check if a list contains unique elements or not. A list will be provided by the user which may have repetitions of elements or unique elements. Here’s one of the simplest methods to solve this problem. we will use the set function in our program. So, before going to solve this we will learn a little bit about the set function.

What is a set function?

A set is a collection of elements in which elements are in random order and there are no duplicates of elements. It is mostly used to solve a mathematical problem like union, the intersection of arrays, symmetric difference, etc.

 Python program to check a list contains unique elements or not

There are some steps that we use to solve this problem in a simple way using Python programming language.

  1. Initially, we will use the set function to remove duplicate elements from the list because the set function does not accept any elements twice. This step will decrease the length of the list.
  2. In the end, you compare the lengths of the original list and the list that comes after the operation of the set. If they are different then the list has contained duplicate elements otherwise it has unique elements.

Python program:-

Let’s assume that a list1 is the list provided by the user.

list1=[3,4,5,3,5,7,9,645,6,8,34,23,2,67,87,45,5,44,2,5885,4,1,4,6,8,858,9,90]

list1=[3,4,5,3,5,7,9,645,6,8,34,23,2,67,87,45,5,44,2,5885,4,1,4,6,8,858,9,90]
list2=list(set(list1))
if len(list2)==len(list1):
print('List has unique elements.')
else:
print('List has duplicate elements.')

Output:-

List has duplicate elements.

So Guy’s, I hope you find it useful.

You may also read:

Leave a Reply

Your email address will not be published. Required fields are marked *