I e got a set of elemnt. the task is to get the number of unique elements. I wrote the following:
import numpy as np
tokens1 = set(["a", "b", "c", "c"])
print(np.unique(tokens1))
print(np.unique(tokens1).size)
The result is
[{'c', 'b', 'a'}]
1
How do i get the correct number - 3? Should have i simply used something other than np.unique in the first place? there might be a better way to get hat i want.
In order to get the number of unique elements in a set, you can simply call len()
on the set. To modify your existing code:
tokens1 = set(["a", "b", "c", "c"])
print(len(tokens1))
# prints: 3
This is because a set already removes duplicates. You don't need to use both a set AND np.unique()
.
If you wanted to use np.unique()
instead, you could modify your code to be:
tokens1 = np.unique(["a", "b", "c", "c"])
print(len(tokens1))
# prints: 3