How do I count occurrence of unique values inside a list

PythonArraysVariablesLoopsUnique

Python Problem Overview


So I'm trying to make this program that will ask the user for input and store the values in an array / list.
Then when a blank line is entered it will tell the user how many of those values are unique.
I'm building this for real life reasons and not as a problem set.

enter: happy
enter: rofl
enter: happy
enter: mpg8
enter: Cpp
enter: Cpp
enter:
There are 4 unique words!

My code is as follows:

# ask for input
ipta = raw_input("Word: ")

# create list 
uniquewords = [] 
counter = 0
uniquewords.append(ipta)

a = 0   # loop thingy
# while loop to ask for input and append in list
while ipta: 
  ipta = raw_input("Word: ")
  new_words.append(input1)
  counter = counter + 1

for p in uniquewords:

..and that's about all I've gotten so far.
I'm not sure how to count the unique number of words in a list?
If someone can post the solution so I can learn from it, or at least show me how it would be great, thanks!

Python Solutions


Solution 1 - Python

In addition, use collections.Counter to refactor your code:

from collections import Counter

words = ['a', 'b', 'c', 'a']

Counter(words).keys() # equals to list(set(words))
Counter(words).values() # counts the elements' frequency

Output:

['a', 'c', 'b']
[2, 1, 1]

Solution 2 - Python

You can use a set to remove duplicates, and then the len function to count the elements in the set:

len(set(new_words))

Solution 3 - Python

values, counts = np.unique(words, return_counts=True)

More Detail
import numpy as np

words = ['b', 'a', 'a', 'c', 'c', 'c']
values, counts = np.unique(words, return_counts=True)

The function numpy.unique returns sorted unique elements of the input list together with their counts:

['a', 'b', 'c']
[2, 1, 3]

Solution 4 - Python

Use a set:

words = ['a', 'b', 'c', 'a']
unique_words = set(words)             # == set(['a', 'b', 'c'])
unique_word_count = len(unique_words) # == 3

Armed with this, your solution could be as simple as:

words = []
ipta = raw_input("Word: ")

while ipta:
  words.append(ipta)
  ipta = raw_input("Word: ")

unique_word_count = len(set(words))

print "There are %d unique words!" % unique_word_count

Solution 5 - Python

aa="XXYYYSBAA"
bb=dict(zip(list(aa),[list(aa).count(i) for i in list(aa)]))
print(bb)
# output:
# {'X': 2, 'Y': 3, 'S': 1, 'B': 1, 'A': 2}

Solution 6 - Python

For ndarray there is a numpy method called unique:

np.unique(array_name)

Examples:

>>> np.unique([1, 1, 2, 2, 3, 3])
array([1, 2, 3])
>>> a = np.array([[1, 1], [2, 3]])
>>> np.unique(a)
array([1, 2, 3])

For a Series there is a function call value_counts():

Series_name.value_counts()

Solution 7 - Python

If you would like to have a histogram of unique values here's oneliner

import numpy as np    
unique_labels, unique_counts = np.unique(labels_list, return_counts=True)
labels_histogram = dict(zip(unique_labels, unique_counts))

Solution 8 - Python

How about:

import pandas as pd
#List with all words
words=[]

#Code for adding words
words.append('test')


#When Input equals blank:
pd.Series(words).nunique()

It returns how many unique values are in a list

Solution 9 - Python

ipta = raw_input("Word: ") ## asks for input
words = [] ## creates list
unique_words = set(words)

Solution 10 - Python

Although a set is the easiest way, you could also use a dict and use some_dict.has(key) to populate a dictionary with only unique keys and values.

Assuming you have already populated words[] with input from the user, create a dict mapping the unique words in the list to a number:

word_map = {}
i = 1
for j in range(len(words)):
    if not word_map.has_key(words[j]):
        word_map[words[j]] = i
        i += 1                                                             
num_unique_words = len(new_map) # or num_unique_words = i, however you prefer

Solution 11 - Python

Other method by using pandas

import pandas as pd

LIST = ["a","a","c","a","a","v","d"]
counts,values = pd.Series(LIST).value_counts().values, pd.Series(LIST).value_counts().index
df_results = pd.DataFrame(list(zip(values,counts)),columns=["value","count"])

You can then export results in any format you want

Solution 12 - Python

You can use get method:

lst = ['a', 'b', 'c', 'c', 'c', 'd', 'd']

dictionary = {}
for item in lst:
    dictionary[item] = dictionary.get(item, 0) + 1
    
print(dictionary)

Output:

{'a': 1, 'b': 1, 'c': 3, 'd': 2}

Solution 13 - Python

The following should work. The lambda function filter out the duplicated words.

inputs=[]
input = raw_input("Word: ").strip()
while input:
    inputs.append(input)
    input = raw_input("Word: ").strip()
uniques=reduce(lambda x,y: ((y in x) and x) or x+[y], inputs, [])
print 'There are', len(uniques), 'unique words'

Solution 14 - Python

I'd use a set myself, but here's yet another way:

uniquewords = []
while True:
    ipta = raw_input("Word: ")
    if ipta == "":
        break
    if not ipta in uniquewords:
        uniquewords.append(ipta)
print "There are", len(uniquewords), "unique words!"

Solution 15 - Python

ipta = raw_input("Word: ") ## asks for input
words = [] ## creates list

while ipta: ## while loop to ask for input and append in list
  words.append(ipta)
  ipta = raw_input("Word: ")
  words.append(ipta)
#Create a set, sets do not have repeats
unique_words = set(words)

print "There are " +  str(len(unique_words)) + " unique words!"

Solution 16 - Python

This is my own version

def unique_elements():
    elem_list = []
    dict_unique_word = {}
    for i in range(5):# say you want to check for unique words from five given words
        word_input = input('enter element: ')
        elem_list.append(word_input)
        if word_input not in dict_unique_word:
            dict_unique_word[word_input] = 1
        else:
            dict_unique_word[word_input] += 1
    return elem_list, dict_unique_word
result_1, result_2 = unique_elements() 
# result_1 holds the list of all inputted elements
# result_2 contains unique words with their count
print(result_2)

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionJoel Aqu.View Question on Stackoverflow
Solution 1 - PythonVidulView Answer on Stackoverflow
Solution 2 - PythoncodeboxView Answer on Stackoverflow
Solution 3 - PythonJames HirschornView Answer on Stackoverflow
Solution 4 - PythonLinus ThielView Answer on Stackoverflow
Solution 5 - PythonMadJayhawkView Answer on Stackoverflow
Solution 6 - Pythonuser78692View Answer on Stackoverflow
Solution 7 - PythonEvalds UrtansView Answer on Stackoverflow
Solution 8 - Pythonjohn_dataView Answer on Stackoverflow
Solution 9 - Pythonuser1590499View Answer on Stackoverflow
Solution 10 - PythonJMBView Answer on Stackoverflow
Solution 11 - PythonHazimoRa3dView Answer on Stackoverflow
Solution 12 - PythonBehrooz OstadaghaeeView Answer on Stackoverflow
Solution 13 - PythonJohn WangView Answer on Stackoverflow
Solution 14 - PythonNicola MusattiView Answer on Stackoverflow
Solution 15 - PythonCuriousView Answer on Stackoverflow
Solution 16 - PythonNsikanabasi MikeView Answer on Stackoverflow