How to get Unique Digits of a Number in Python?

Contents

Python – Unique Digits of a Number

To get unique digits in a given number in Python, convert the given number to string, and pass this string to set() method. set() method returns a Python Set containing unique digits. But, this resulting set is a collection of strings. We can change to a list of numbers, using List Comprehension.

Program

In the following program, we read a number from user using input() function, and then find the unique digits in this number.

Python Program

n = int(input())
unique = [int(x) for x in set(str(n))]
print(unique)
Copy

Output #1

112455412
[4, 1, 2, 5]

Output #2

1111122222244 
[4, 1, 2]

References

Summary

In this Python Tutorial, we learned how to find unique digits present in a given number.

Related Tutorials

Code copied to clipboard successfully 👍