**Problem Statement:** Consider that you have been given a list in Python. How will you count the number of unique values in the list?

**Example:** Let’s visualize the problem with the help of an example:

Given: li = [‘a’, ‘a’, ‘b’, ‘c’, ‘b’, ‘d’, ‘d’, ‘a’] Output: The unique values in the given list are ‘a’, ‘b’, ‘c’, ‘d’. Thus the expected output is 4. |

Now that you have a clear picture of what the question demands, let’s dive into the different ways of solving the problem.

**Method 1: The Naive Approach**

**Approach:**

- Create an empty list that will be used to store all the unique elements from the given list. Let’s say that the name of this list
`res`

. - To store the unique elements in the new list that you created previously, simply traverse through all the elements of the given list with the help of a for loop and then check if each value from the given list is present in the list “
`res`

“.- If a particular value from the given list is not present in the newly created list then append it to the list
`res`

. This ensures that each unique value/item from the given list gets stored within`res`

. - If it’s already present, then do not append the value.

- If a particular value from the given list is not present in the newly created list then append it to the list
- Finally, the list
`res`

represents a newly formed list that contains all unique values from the originally given list. All that remains to be done is to find the length of the list`res`

which gives you the number of unique values present in the given list.

**Code:**

# Given list li = ['a', 'a', 'b', 'c', 'b', 'd', 'd', 'a'] res = [] for ele in li: if ele not in res: res.append(ele) print("The count of unique values in the list:", len(res)) # The count of unique values in the list: 4

**Discussion**: Since you have to create an extra list to store the unique values, this approach is not the most efficient way to find and count the unique values in a list as it takes a lot of time and space.

**Method 2: Using set()**

A more effective and pythonic approach to solve the given problem is to use the `set()`

method. Set is a built-in data type that does not contain any duplicate elements.

**Read more about sets here – “The Ultimate Guide to Python Sets“**

**Approach: **Convert the given list into a set using the `set()`

function. Since a set cannot contain duplicate values, only the unique values from the list will be stored within the set. Now that you have all the unique values at your disposal, you can simply count the number of unique values with the help of the `len()`

function.

**Code: **

li = ['a', 'a', 'b', 'c', 'b', 'd', 'd', 'a'] s = set(li) unique_values = len(s) print("The count of unique values in the list:", unique_values) # The count of unique values in the list: 4

You can formulate the above solution in a single line of code by simply chaining both the functions (`set()`

and `len()`

) together, as shown below:

# Given list li = ['a', 'a', 'b', 'c', 'b', 'd', 'd', 'a'] # One-liner print("The count of unique values in the list:", len(set(li)))

**Method** 3: **Using Dictionary fromkeys()**

Python dictionaries have a method known as `fromkeys()`

that is used to return a new dictionary from the given iterable ( such as list, set, string, tuple) as keys and with the specified value. If the value is not specified by default, it will be considered as None.

**Approach: **Well! We all know that keys in a dictionary must be unique. Thus, we will pass the list to the `fromkeys()`

method and then use only the key values of this dictionary to get the unique values from the list. Once we have stored all the unique values of the given list stored into another list, all that remains to be done is to find the length of the list containing the unique values which will return us the number of unique values.

**Code:**

# Given list li = ['a', 'a', 'b', 'c', 'b', 'd', 'd', 'a'] # Using dictionary fromkeys() # list elements get converted to dictionary keys. Keys are always unique! x = dict.fromkeys(li) # storing the keys of the dictionary in a list l2 = list(x.keys()) print("Number of unique values in the list:", len(l2)) # Number of unique values in the list: 4

**Method 4: Using Counter**

Another way to solve the given problem is to use the `Counter`

function from the `collections`

module. The `Counter`

function creates a dictionary where the dictionary’s keys represent the unique items of the list, and the corresponding values represent the count of a key (i.e. the number of occurrences of an item in the list). Once you have the dictionary all you need to do is to extract the keys of the dictionary and store them in a list and then find the length of this list.

from collections import Counter # Given list li = ['a', 'a', 'b', 'c', 'b', 'd', 'd', 'a'] # Creating a list containing the keys (the unique values) key = Counter(li).keys() # Calculating the length to get the count res = len(key) print("The count of unique values in the list:", res) # The count of unique values in the list: 4

**Method 5: Using Numpy Module**

We can also use Python’s Numpy module to get the count of unique values from the list. First, we must import the NumPy module into the code to use the `numpy.unique()`

function that returns the unique values from the list.

**Solution:**

# Importing the numpy module import numpy as np # Given list li = ['a', 'a', 'b', 'c', 'b', 'd', 'd', 'a'] res = [] # Using unique() function from numpy module for ele in np.unique(li): res.append(ele) # Calculating the length to get the count of unique elements count = len(res) print("The count of unique values in the list:", count) # The count of unique values in the list: 4

Another approach is to create an array using the `array()`

function after importing the numpy module. Further, we will use the `unique()`

function to remove the duplicate elements from the list. Finally, we will calculate the length of that array to get the count of the unique elements.

**Solution:**

# Importing the numpy module import numpy as np # Given list li = ['a', 'a', 'b', 'c', 'b', 'd', 'd', 'a'] array = np.array(li) u = np.unique(array) c = len(u) print("The count of unique values in the list:", c) # The count of unique values in the list: 4

**Method 6: Using List Comprehension**

There’s yet another way of solving the given problem. You can use a list comprehension to get the count of each element in the list and then use the `zip()`

function to create a zip object that creates pairs of each item along with the count of each item in the list. Store these paired items as key-value pairs in a dictionary by converting the zip object to a dictionary using the `dict()`

function. Finally, return the dictionary’s keys’ calculated length (using the `len()`

function).

**Code:**

# Given list li = ['a', 'a', 'b', 'c', 'b', 'd', 'd', 'a'] # List comprehension using zip() l2 = dict(zip(li, [li.count(i) for i in li])) # Using len to get the count of unique elements l = len(list(l2.keys())) print("The count of the unique values in the list:", l) # The count of the unique values in the list: 4

**Conclusion**

In this article, we learned the different methods to count the unique values in a list in Python. We looked at how to do this using the counter, sets, numpy module, and list comprehensions. If you found this article helpful and want to receive more interesting solutions and discussions in the future, please **subscribe **and stay tuned!

## Python One-Liners Book: Master the Single Line First!

**Python programmers will improve their computer science skills with these useful one-liners.**

*Python One-Liners* will teach you how to read and write “one-liners”: ** concise statements of useful functionality packed into a single line of code. **You’ll learn how to systematically unpack and understand any line of Python code, and write eloquent, powerfully compressed Python like an expert.

The book’s five chapters cover (1) tips and tricks, (2) regular expressions, (3) machine learning, (4) core data science topics, and (5) useful algorithms.

Detailed explanations of one-liners introduce ** key computer science concepts **and

**. You’ll learn about advanced Python features such as**

*boost your coding and analytical skills**,*

**list comprehension****,**

*slicing***,**

*lambda functions***,**

*regular expressions***and**

*map***functions, and**

*reduce***.**

*slice assignments*You’ll also learn how to:

- Leverage data structures to
**solve real-world problems**, like using Boolean indexing to find cities with above-average pollution - Use
**NumPy basics**such as*array*,*shape*,*axis*,*type*,*broadcasting*,*advanced indexing*,*slicing*,*sorting*,*searching*,*aggregating*, and*statistics* - Calculate basic
**statistics**of multidimensional data arrays and the K-Means algorithms for unsupervised learning - Create more
**advanced regular expressions**using*grouping*and*named groups*,*negative lookaheads*,*escaped characters*,*whitespaces, character sets*(and*negative characters sets*), and*greedy/nongreedy operators* - Understand a wide range of
**computer science topics**, including*anagrams*,*palindromes*,*supersets*,*permutations*,*factorials*,*prime numbers*,*Fibonacci*numbers,*obfuscation*,*searching*, and*algorithmic sorting*

By the end of the book, you’ll know how to ** write Python at its most refined**, and create concise, beautiful pieces of “Python art” in merely a single line.