Home » Python » Python programs

Check all elements are unique or not in Python

Here, we are going to learn how to check all elements are unique or not in Python programming language?
Submitted by IncludeHelp, on March 27, 2020

Here, we are implementing a python program to check whether all elements of a list are unique or not?

It's very simple to check, by following two steps

  1. Convert the list in a set (as you should know that set contains the unique elements) – it will remove the duplicate elements if any.
  2. Then, compare the length of the list and set – if both are the same then all elements are unique.

Program:

# function to check unique
def check_unique(x):
  return len(x) == len(set(x))

# lists
x = [10, 20, 30, 40,50]
y = [10, 20, 20, 20, 20]
z = [10, 10, 10, 10, 10]

print("x: ", x)
print("len(x): ", len(x))
print("set(x): ", set(x))
print("len(set(x)): ", len(set(x)))
print("check_unique(x): ", check_unique(x))
print()

print("y: ", y)
print("len(y): ", len(y))
print("set(y): ", set(y))
print("len(set(y)): ", len(set(y)))
print("check_unique(y): ", check_unique(y))
print()

print("z: ", z)
print("len(z): ", len(z))
print("set(z): ", set(z))
print("len(set(z)): ", len(set(z)))
print("check_unique(z): ", check_unique(z))
print()

Output

x:  [10, 20, 30, 40, 50]
len(x):  5
set(x):  {40, 10, 50, 20, 30}
len(set(x)):  5
check_unique(x):  True

y:  [10, 20, 20, 20, 20]
len(y):  5
set(y):  {10, 20}
len(set(y)):  2
check_unique(y):  False

z:  [10, 10, 10, 10, 10]
len(z):  5
set(z):  {10}
len(set(z)):  1
check_unique(z):  False





Comments and Discussions

Ad: Are you a blogger? Join our Blogging forum.





Languages: » C » C++ » C++ STL » Java » Data Structure » C#.Net » Android » Kotlin » SQL
Web Technologies: » PHP » Python » JavaScript » CSS » Ajax » Node.js » Web programming/HTML
Solved programs: » C » C++ » DS » Java » C#
Aptitude que. & ans.: » C » C++ » Java » DBMS
Interview que. & ans.: » C » Embedded C » Java » SEO » HR
CS Subjects: » CS Basics » O.S. » Networks » DBMS » Embedded Systems » Cloud Computing
» Machine learning » CS Organizations » Linux » DOS
More: » Articles » Puzzles » News/Updates


© https://www.includehelp.com some rights reserved.