Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Optimized code to check the element of list unique or not

python3 program that takes input a list and output if it is unique or not. The following is an example:

list_a = [1,2,3,4,5] #unique
list_b = [1,2,2,3,4] #not unique

I have wrote a python3 script for this problem:

for i in range(len(list_a)):
   j = i+1
   for j in range(len(list_a)):
      if list_a[i] == list_a[j]:
         print ("not unique")
      else:
         print ("unique")

Is this the only way to check it. I bet it isn't! I want some optimized code that is equivalent to above or simply that ouputs "unique" or "not unique" for a given list. Thank you in advance.

like image 312
SujitS Avatar asked Nov 27 '22 21:11

SujitS


2 Answers

The easiest way to do this is compare length of set of given list with length of list:

if len(l) != len(set(l)):
    # not unique
like image 60
awesoon Avatar answered Dec 06 '22 16:12

awesoon


You can use all() and sets, this will short-circuit as soon as a repeated item is found.

>>> def solve(lis):
...     seen = set()
...     return all(item not in seen and not seen.add(item) for item in lis)
... 
>>> solve(range(5))
True
>>> solve([1,2,2,3,4])
False
like image 28
Ashwini Chaudhary Avatar answered Dec 06 '22 14:12

Ashwini Chaudhary