Search code examples
pythonlistunique-values

Python List and count all unique values in list


I have a list:

originalList = ['Item1', 'Item1', 'Item1', 'Item2', 'Item2', 'Item3', 'Item4']

I need to create two lists based off of the originalList

The first list I need, should list all unique items, such as:

['Item1', 'Item2', 'Item3', 'Item4']

While the other should list the count of each unique value:

[3, 2, 1, 1]

Please help


Solution

  • You can use Counter in the following way:

    from collections import Counter
    res = dict(Counter(originalList))
    

    And getting the keys will give the resulted list and the values will be the count of each element.

    To get the 2 lists:

    keys, values = map(list, zip(*d.items()))