Create an account


Thread Rating:
  • 0 Vote(s) - 0 Average
  • 1
  • 2
  • 3
  • 4
  • 5
[Tut] How to Count the Number of Unique Values in a List in Python?

#1
How to Count the Number of Unique Values in a List in Python?

<div>
<div class="kk-star-ratings kksr-auto kksr-align-left kksr-valign-top" data-payload="{&quot;align&quot;:&quot;left&quot;,&quot;id&quot;:&quot;804483&quot;,&quot;slug&quot;:&quot;default&quot;,&quot;valign&quot;:&quot;top&quot;,&quot;ignore&quot;:&quot;&quot;,&quot;reference&quot;:&quot;auto&quot;,&quot;class&quot;:&quot;&quot;,&quot;count&quot;:&quot;0&quot;,&quot;readonly&quot;:&quot;&quot;,&quot;score&quot;:&quot;0&quot;,&quot;best&quot;:&quot;5&quot;,&quot;gap&quot;:&quot;5&quot;,&quot;greet&quot;:&quot;Rate this post&quot;,&quot;legend&quot;:&quot;0\/5 - (0 votes)&quot;,&quot;size&quot;:&quot;24&quot;,&quot;width&quot;:&quot;0&quot;,&quot;_legend&quot;:&quot;{score}\/{best} - ({count} {votes})&quot;,&quot;font_factor&quot;:&quot;1.25&quot;}">
<div class="kksr-stars">
<div class="kksr-stars-inactive">
<div class="kksr-star" data-star="1" style="padding-right: 5px">
<div class="kksr-icon" style="width: 24px; height: 24px;"></div>
</p></div>
<div class="kksr-star" data-star="2" style="padding-right: 5px">
<div class="kksr-icon" style="width: 24px; height: 24px;"></div>
</p></div>
<div class="kksr-star" data-star="3" style="padding-right: 5px">
<div class="kksr-icon" style="width: 24px; height: 24px;"></div>
</p></div>
<div class="kksr-star" data-star="4" style="padding-right: 5px">
<div class="kksr-icon" style="width: 24px; height: 24px;"></div>
</p></div>
<div class="kksr-star" data-star="5" style="padding-right: 5px">
<div class="kksr-icon" style="width: 24px; height: 24px;"></div>
</p></div>
</p></div>
<div class="kksr-stars-active" style="width: 0px;">
<div class="kksr-star" style="padding-right: 5px">
<div class="kksr-icon" style="width: 24px; height: 24px;"></div>
</p></div>
<div class="kksr-star" style="padding-right: 5px">
<div class="kksr-icon" style="width: 24px; height: 24px;"></div>
</p></div>
<div class="kksr-star" style="padding-right: 5px">
<div class="kksr-icon" style="width: 24px; height: 24px;"></div>
</p></div>
<div class="kksr-star" style="padding-right: 5px">
<div class="kksr-icon" style="width: 24px; height: 24px;"></div>
</p></div>
<div class="kksr-star" style="padding-right: 5px">
<div class="kksr-icon" style="width: 24px; height: 24px;"></div>
</p></div>
</p></div>
</div>
<div class="kksr-legend" style="font-size: 19.2px;"> <span class="kksr-muted">Rate this post</span> </div>
</div>
<p><strong>Problem Statement:</strong> Consider that you have been given a list in Python. How will you count the number of unique values in the list?</p>
<p><strong>Example:</strong> Let’s visualize the problem with the help of an example:</p>
<figure class="wp-block-table is-style-stripes">
<table>
<tbody>
<tr>
<td><strong>Given: </strong><br />li = [‘a’, ‘a’, ‘b’, ‘c’, ‘b’, ‘d’, ‘d’, ‘a’]<br /><strong>Output: </strong>The unique values in the given list are ‘a’, ‘b’, ‘c’, ‘d’. Thus the expected output is <strong>4</strong>.</td>
</tr>
</tbody>
</table>
</figure>
<p>Now that you have a clear picture of what the question demands, let’s dive into the different ways of solving the problem. </p>
<h2><strong>Method 1: The Naive Approach</strong></h2>
<p><strong>Approach:</strong> </p>
<ul>
<li>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 <code>res</code>.</li>
<li>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 “<code>res</code>“.
<ul>
<li>If a particular value from the given list is not present in the newly created list then append it to the list <code>res</code>. This ensures that each unique value/item from the given list gets stored within <code>res</code>. </li>
<li>If it’s already present, then do not append the value.</li>
</ul>
</li>
<li>Finally, the list <code>res</code> 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 <code>res</code> which gives you the number of unique values present in the given list. </li>
</ul>
<p><strong>Code:</strong></p>
<pre class="EnlighterJSRAW" data-enlighter-language="generic" data-enlighter-theme="" data-enlighter-highlight="" data-enlighter-linenumbers="" data-enlighter-lineoffset="" data-enlighter-title="" data-enlighter-group=""># 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</pre>
<p><strong>Discussion</strong>: 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.</p>
<h2><strong>Method 2: Using set()</strong></h2>
<p>A more effective and pythonic approach to solve the given problem is to use the <code>set()</code> method. Set is a built-in data type that does not contain any duplicate elements.</p>
<p class="has-background" style="background-color:#fcfcb9"><strong>Read more about sets here – “<a rel="noreferrer noopener" href="https://blog.finxter.com/sets-in-python/" target="_blank">The Ultimate Guide to Python Sets</a>“</strong></p>
<p> <strong>Approach: </strong>Convert the given list into a set using the <code>set()</code> 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 <code>len()</code> function.</p>
<p><strong>Code: </strong></p>
<pre class="EnlighterJSRAW" data-enlighter-language="generic" data-enlighter-theme="" data-enlighter-highlight="" data-enlighter-linenumbers="" data-enlighter-lineoffset="" data-enlighter-title="" data-enlighter-group="">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</pre>
<p>You can formulate the above solution in a single line of code by simply chaining both the functions (<code>set()</code> and <code>len()</code>) together, as shown below:</p>
<pre class="EnlighterJSRAW" data-enlighter-language="generic" data-enlighter-theme="" data-enlighter-highlight="" data-enlighter-linenumbers="" data-enlighter-lineoffset="" data-enlighter-title="" data-enlighter-group=""># 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)))</pre>
<h2><strong>Method</strong> 3: <strong>Using <a rel="noreferrer noopener" href="https://blog.finxter.com/python-dictionary/" target="_blank">Dictionary </a>fromkeys()</strong></h2>
<p>Python dictionaries have a method known as <code>fromkeys()</code> 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. </p>
<p><strong>Approach: </strong>Well! We all know that keys in a dictionary must be unique. Thus, we will pass the list to the <code>fromkeys()</code> 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. </p>
<p><strong>Code:</strong></p>
<pre class="EnlighterJSRAW" data-enlighter-language="generic" data-enlighter-theme="" data-enlighter-highlight="" data-enlighter-linenumbers="" data-enlighter-lineoffset="" data-enlighter-title="" data-enlighter-group=""># 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</pre>
<h2><strong>Method 4: Using Counter</strong></h2>
<p>Another way to solve the given problem is to use the <code>Counter</code> function from the <code>collections</code> module. The <code>Counter</code> 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. </p>
<pre class="EnlighterJSRAW" data-enlighter-language="generic" data-enlighter-theme="" data-enlighter-highlight="" data-enlighter-linenumbers="" data-enlighter-lineoffset="" data-enlighter-title="" data-enlighter-group="">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</pre>
<h2><strong>Method 5: Using <a href="https://blog.finxter.com/numpy-tutorial/" target="_blank" rel="noreferrer noopener">Numpy</a> Module</strong></h2>
<p>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 <code>numpy.unique()</code> function that returns the unique values from the list.</p>
<p><strong>Solution:</strong></p>
<pre class="EnlighterJSRAW" data-enlighter-language="generic" data-enlighter-theme="" data-enlighter-highlight="" data-enlighter-linenumbers="" data-enlighter-lineoffset="" data-enlighter-title="" data-enlighter-group=""># 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</pre>
<p>Another approach is to create an array using the <code>array()</code> function after importing the numpy module. Further, we will use the <code>unique()</code> 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.</p>
<p><strong>Solution:</strong></p>
<pre class="EnlighterJSRAW" data-enlighter-language="generic" data-enlighter-theme="" data-enlighter-highlight="" data-enlighter-linenumbers="" data-enlighter-lineoffset="" data-enlighter-title="" data-enlighter-group=""># 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</pre>
<h2><strong>Method 6: Using <a rel="noreferrer noopener" href="https://blog.finxter.com/list-comprehension/" target="_blank">List Comprehension</a></strong></h2>
<p>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 <code>zip()</code> 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 <code>dict()</code> function. Finally, return the dictionary’s keys’ calculated length (using the <code>len()</code> function).</p>
<p><strong>Code:</strong></p>
<pre class="EnlighterJSRAW" data-enlighter-language="generic" data-enlighter-theme="" data-enlighter-highlight="" data-enlighter-linenumbers="" data-enlighter-lineoffset="" data-enlighter-title="" data-enlighter-group=""># 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</pre>
<h2><strong>Conclusion</strong></h2>
<p>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 <strong><a rel="noreferrer noopener" href="https://blog.finxter.com/subscribe" target="_blank">subscribe </a></strong>and stay tuned!</p>
<hr class="wp-block-separator has-alpha-channel-opacity" />
<h2>Python One-Liners Book: Master the Single Line First!</h2>
<p><strong>Python programmers will improve their computer science skills with these useful one-liners.</strong></p>
<div class="wp-block-image">
<figure class="aligncenter size-medium is-resized"><a href="https://www.amazon.com/gp/product/B07ZY7XMX8" target="_blank" rel="noopener noreferrer"><img loading="lazy" src="https://blog.finxter.com/wp-content/uploads/2020/06/3D_cover-1024x944.jpg" alt="Python One-Liners" class="wp-image-10007" width="512" height="472" srcset="https://blog.finxter.com/wp-content/uploads/2020/06/3D_cover-scaled.jpg 1024w, https://blog.finxter.com/wp-content/uplo...00x277.jpg 300w, https://blog.finxter.com/wp-content/uplo...68x708.jpg 768w" sizes="(max-width: 512px) 100vw, 512px" /></a></figure>
</div>
<p><a href="https://amzn.to/2WAYeJE" target="_blank" rel="noreferrer noopener" title="https://amzn.to/2WAYeJE"><em>Python One-Liners</em> </a>will teach you how to read and write “one-liners”: <strong><em>concise statements of useful functionality packed into a single line of code. </em></strong>You’ll learn how to systematically unpack and understand any line of Python code, and write eloquent, powerfully compressed Python like an expert.</p>
<p>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. </p>
<p>Detailed explanations of one-liners introduce <strong><em>key computer science concepts </em></strong>and<strong><em> boost your coding and analytical skills</em></strong>. You’ll learn about advanced Python features such as <em><strong>list comprehension</strong></em>, <strong><em>slicing</em></strong>, <strong><em>lambda functions</em></strong>, <strong><em>regular expressions</em></strong>, <strong><em>map </em></strong>and <strong><em>reduce </em></strong>functions, and <strong><em>slice assignments</em></strong>. </p>
<p>You’ll also learn how to:</p>
<ul>
<li>Leverage data structures to <strong>solve real-world problems</strong>, like using Boolean indexing to find cities with above-average pollution</li>
<li>Use <strong>NumPy basics</strong> such as <em>array</em>, <em>shape</em>, <em>axis</em>, <em>type</em>, <em>broadcasting</em>, <em>advanced indexing</em>, <em>slicing</em>, <em>sorting</em>, <em>searching</em>, <em>aggregating</em>, and <em>statistics</em></li>
<li>Calculate basic <strong>statistics </strong>of multidimensional data arrays and the K-Means algorithms for unsupervised learning</li>
<li>Create more <strong>advanced regular expressions</strong> using <em>grouping </em>and <em>named groups</em>, <em>negative lookaheads</em>, <em>escaped characters</em>, <em>whitespaces, character sets</em> (and <em>negative characters sets</em>), and <em>greedy/nongreedy operators</em></li>
<li>Understand a wide range of <strong>computer science topics</strong>, including <em>anagrams</em>, <em>palindromes</em>, <em>supersets</em>, <em>permutations</em>, <em>factorials</em>, <em>prime numbers</em>, <em>Fibonacci </em>numbers, <em>obfuscation</em>, <em>searching</em>, and <em>algorithmic sorting</em></li>
</ul>
<p>By the end of the book, you’ll know how to <strong><em>write Python at its most refined</em></strong>, and create concise, beautiful pieces of “Python art” in merely a single line.</p>
<p><strong><a href="https://amzn.to/2WAYeJE" target="_blank" rel="noreferrer noopener" title="https://amzn.to/2WAYeJE"><em>Get your Python One-Liners on Amazon!!</em></a></strong></p>
</div>


https://www.sickgaming.net/blog/2022/10/...in-python/
Reply



Forum Jump:


Users browsing this thread:
2 Guest(s)

Forum software by © MyBB Theme © iAndrew 2016