Printing the number of different numbers in python

Question:

I would like to ask a question please regarding printing the number of different numbers in python.

for example:
Let us say that I have the following list:

X = [5, 5, 5] 

Since here we have only one number, I want to build a code that can recognize that we have only one number here so the output must be:

1
The number is: 5 

Let us say that I have the following list:

X = [5,4,5]

Since here we have two numbers (5 and 4), I want to the code to recognize that we have only two numbers here so the output must be:

2
The numbers are: 4, 5

Let us say that I have the following list:

X = [24,24,24,24,24,24,24,24,26,26,26,26,26,26,26,26]

Since here we have two numbers (24 and 26), I want to the code to recognize that we have only two numbers here so the output must be:

2
The numbers are: 24, 26
Asked By: Mhmoud Khadija

||

Answers:

You could keep track of unique numbers with a set object:

X = [1,2,3,3,3]
S = set(X)
n = len(S)
print(n, S)  # 3 {1,2,3}

Bear in mind sets are unordered, so you would need to convert back to a list and sort them if needed.

Answered By: asena

you can change this list into set, it will remove duplicate, then you can change it again into list.

list(set(X))
Answered By: Karthik Raja

You can try numpy.unique, and use len() on the result

Answered By: yoooPai
Categories: questions Tags: , ,
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.