python find unique values in list code example
Example 1: python list with only unique values
my_list = list(set(my_list))
Example 2: python list distinct
my_list = list(set(my_list))
Example 3: how to find unique values in list in python
mylist = ['nowplaying', 'PBS', 'PBS', 'nowplaying', 'job', 'debate', 'thenandnow']
myset = set(mylist)
print(myset)
Example 4: return position of a unique value in python array
In [304]: array = np.array([1, 1, 2, 3, 2, 1, 2, 3])
In [305]: np.unique(array) # unique values in `array`
Out[305]: array([1, 2, 3])
In [306]: array == 1 # retrieve a boolean mask where elements are equal to 1
Out[306]: array([ True, True, False, False, False, True, False, False])
In [307]: (array == 1).nonzero()[0] # get the `True` indices for the operation above
Out[307]: array([0, 1, 5])
Example 5: python count unique values in list
len(set(["word1", "word1", "word2", "word3"]))
# set is like a list but it removes duplicates
# len counts the number of things inside the set
Example 6: return position of a unique value in python array
def partition(array):
return {i: (array == i).nonzero()[0] for i in np.unique(array)}