![]() |
|
[Tut] How to Count the Number of Unique Values in a List in Python? - Printable Version +- Sick Gaming (https://sickgaming.net) +-- Forum: Programming (https://sickgaming.net/forum-76.html) +--- Forum: Python (https://sickgaming.net/forum-83.html) +--- Thread: [Tut] How to Count the Number of Unique Values in a List in Python? (/thread-100110.html) |
[Tut] How to Count the Number of Unique Values in a List in Python? - xSicKxBot - 10-19-2022 How to Count the Number of Unique Values in a List in Python? Rate this post 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. [b]Method 1: The Naive Approach[/b] Approach:
Code: 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: 4Discussion: 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. [b]Method 2: Using set()[/b] A more effective and pythonic approach to solve the given problem is to use the Code: set()Read more about sets here – “The Ultimate Guide to Python Sets“ Approach: Convert the given list into a set using the Code: set()Code: len()Code: 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: 4You can formulate the above solution in a single line of code by simply chaining both the functions ( Code: set()Code: len()Code: # 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)))Python dictionaries have a method known as Code: fromkeys()Approach: Well! We all know that keys in a dictionary must be unique. Thus, we will pass the list to the Code: fromkeys()Code: 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: 4Another way to solve the given problem is to use the Code: CounterCode: collectionsCode: CounterCode: 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: 4We 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 Code: numpy.unique()Solution: Code: # 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: 4Another approach is to create an array using the Code: array()Code: unique()Solution: Code: # 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: 4There’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 Code: zip()Code: dict()Code: len()Code: 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: 4In 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-Linerswill 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 boost your coding and analytical skills. You’ll learn about advanced Python features such as list comprehension, slicing, lambda functions, regular expressions, map and reduce functions, and slice assignments. You’ll also learn how to:
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. Get your Python One-Liners on Amazon!! |