# Count the number of unique elements in a List in Python Last updated: Sep 22, 2022 Photo from Unsplash

## Count the number of unique elements in a List in Python#

Use the `set()` class to count the number of unique elements in a list, e.g. `result = len(set(my_list))`. The `set()` class will convert the list to a `set` of unique elements and the `len()` function will return the total number of unique elements in the list.

main.py
```Copied!```my_list = ['a', 'b', 'a', 'b']

result = len(set(my_list))
print(result)  # 👉️ 2
``````

The set() class takes an iterable optional argument and returns a new `set` object with elements taken from the iterable.

main.py
```Copied!```my_list = ['a', 'b', 'a', 'b']

my_set = set(my_list)
print(my_set) # 👉️ {'b', 'a'}
``````
Set objects store an unordered collection of unique elements, so converting the list to a `set` removes all duplicate elements.

The last step is to use the `len()` function to get the total count.

The len() function returns the length (the number of items) of an object.

The argument the function takes may be a sequence (a string, tuple, list, range or bytes) or a collection (a dictionary, set, or frozen set).

You can also use the `Counter` class if you need to get the unique elements in the list.

main.py
```Copied!```from collections import Counter

my_list = ['a', 'b', 'a', 'b']

unique_elements = list(Counter(my_list))
print(unique_elements)  # 👉️ ['a', 'b']

occurrences = list(Counter(my_list).values())
print(occurrences)  # 👉️ [2, 2]

my_dict = dict(Counter(my_list))
print(my_dict)  # 👉️ {'a': 2, 'b': 2}
``````

The `Counter` class is a subclass of `dict` and is used for counting items.

If you use `numpy`, you can also use the `numpy.unique` method.

main.py
```Copied!```import numpy as np

my_list = ['a', 'b', 'a', 'b']

elements, occurrences = np.unique(my_list, return_counts=True)
print(elements) # 👉️ ['a' 'b']
print(occurrences) # 👉️ [2 2]
``````

The numpy.unique method returns the sorted unique elements of an array.

We set the `return_counts` argument to `True` to get the number of times each unique item appears in the list.

Alternatively, you can use the `dict.fromkeys()` method.

## Count the number of unique elements in a List using dict.fromkeys()#

To count the number of unique elements in a list:

1. Use the `dict.fromkeys()` method to create a dictionary from the list.
2. Use the `len()` function to get the number of unique elements in the list.
main.py
```Copied!```my_list = ['a', 'b', 'a', 'b']

result = len(dict.fromkeys(my_list))
print(result)  # 👉️ 2

print(list(dict.fromkeys(my_list))) # 👉️ ['a', 'b']
``````

The dict.fromkeys method takes an iterable and a value and creates a new dictionary with keys from the iterable and values set to the provided value.

main.py
```Copied!```my_list = ['a', 'b', 'a', 'b']

# 👇️ {'a': None, 'b': None}
print(dict.fromkeys(my_list))
``````

Dictionary keys are unique, so any duplicate elements get removed.

The last step is to use the `len()` function to get the total count of unique elements.

Alternatively, you can use a simple `for` loop.

## Count the number of unique elements in a List using for loop#

To count the number of unique elements in a list:

1. Declare a new variable that stores an empty list.
2. Use a `for` loop to iterate over the original list.
3. Use the `list.append()` method to append all unique elements to the new list.
4. Use the `len()` function to get the length of the list.
main.py
```Copied!```my_list = ['a', 'b', 'a', 'b']

unique_elements = []

for item in my_list:
if item not in unique_elements:
unique_elements.append(item)

result = len(unique_elements)
print(result) # 👉️ 2

print(unique_elements) # 👉️ ['a', 'b']
``````

We used a `for` loop to iterate over the original list.

On each iteration, we use the `not in` operator to check if the element is not present in the list of unique elements.

If the condition is met, we use the `list.append()` method to append the value to the list.

The in operator tests for membership. For example, `x in l` evaluates to `True` if `x` is a member of `l`, otherwise it evaluates to `False`.

`x not in l` returns the negation of `x in l`.

The list.append() method adds an item to the end of the list.

main.py
```Copied!```my_list = ['bobby', 'hadz']

my_list.append('com')

print(my_list)  # 👉️ ['bobby', 'hadz', 'com']
``````

The last step is to use the `len()` function to get the length of the list of unique elements.

I wrote a book in which I share everything I know about how to become a better, more efficient programmer. You can use the search field on my Home Page to filter through all of my articles.