Check if all array elements are distinct in Python



Suppose we have a list of numbers called nums, we have to check whether all elements in nums are unique or not.

So, if the input is like nums = [2, 3, 6, 5, 1, 8], then the output will be True as all elements are unique.

To solve this, we will follow these steps −

  • n := size of l
  • s := a new set
  • for i in range 0 to n, do
    • insert l[i] into s
  • return true when size of s is same as size of l, otherwise false

Let us see the following implementation to get better understanding −

Example

 Live Demo

def solve(l) :
   n = len(l)
   s = set()
   for i in range(0, n):
      s.add(l[i])
   return (len(s) == len(l))
l = [2, 3, 6, 5, 1, 8]
print(solve(l))

Input

[2, 3, 6, 5, 1, 8]

Output

True

Advertisements