Create an account


Thread Rating:
  • 0 Vote(s) - 0 Average
  • 1
  • 2
  • 3
  • 4
  • 5
[Tut] Python: How to Count Elements in a List Matching a Condition?

#1
Python: How to Count Elements in a List Matching a Condition?

<div><p>I stumbled across this question when browsing through StackOverflow and it got me thinking: what’s the best way to count the number of elements in a list that match a certain condition? Can you generalize this way to both general conditions (e.g. <code>x>3</code>) and regular expressions (e.g. <code>'a.*'</code>)? </p>
<figure class="wp-block-embed-youtube wp-block-embed is-type-video is-provider-youtube wp-embed-aspect-16-9 wp-has-aspect-ratio">
<div class="wp-block-embed__wrapper">
<div class="ast-oembed-container"><iframe title="Python: How to Count Elements in a List Matching a Condition? [A No-BS Framework]" width="1400" height="788" src="https://www.youtube.com/embed/nOwGa4gRjFs?feature=oembed" frameborder="0" allow="accelerometer; autoplay; encrypted-media; gyroscope; picture-in-picture" allowfullscreen></iframe></div>
</div>
</figure>
<p><strong>Short answer: you can count the number of elements <code>x</code> that match a certain <code>condition(x)</code> by using the one-liner expression <code>sum(condition(x) for x in lst)</code>. This creates a generator expression that returns <code>True</code> for each element that satisfies the condition and <code>False</code> otherwise. Since the <code>True</code> and <code>False</code> values are represented by integer 1 and 0 values, you get the number of matching elements by summing over the iterable.</strong></p>
<p>Try it yourself with the interactive code shell:</p>
<figure class="wp-block-embed-wordpress wp-block-embed is-type-wp-embed is-provider-repl-it">
<div class="wp-block-embed__wrapper">
<iframe title="countCondition" class="wp-embedded-content" sandbox="allow-scripts" security="restricted" src="https://repl.it/@finxter/countCondition?lite=true#?secret=Wku9PHjial" data-secret="Wku9PHjial" width="800" height="600" frameborder="0"></iframe>
</div>
</figure>
<p>In case, the browser interpreter doesn’t show up in your browser, here’s the raw Python code:</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="">## FRAMEWORK FOR CONDITIONAL COUNT ## # Define any condition here
def condition(x): return x > 10 # Create the list
lst = [10, 11, 42, 1, 2, 3] # Count the number of matching elements
print(sum(condition(x) for x in lst))
# What's the output?</pre>
<p><strong>Related articles:</strong></p>
<ul>
<li><a href="https://blog.finxter.com/python-list-methods/" target="_blank" rel="noreferrer noopener">Python List Methods</a></li>
<li><a href="https://blog.finxter.com/python-list-count/" target="_blank" rel="noreferrer noopener">Python List Count()</a></li>
</ul>
<h2>Python List Count With Condition</h2>
<p>How can you count elements under a certain condition in <a href="https://blog.finxter.com/python-crash-course/" target="_blank" rel="noreferrer noopener">Python</a>? For example, what if you want to count all even values in a list? Or all prime numbers? Or all strings that start with a certain character? There are multiple ways to accomplish this, let’s discuss them one by one.</p>
<p>Say, you have a condition for each element <code>x</code>. Let’s make it a function with the name <code>condition(x)</code>. You can define any condition you want—just put it in your function. For example this condition returns True for all elements that are greater than the integer 10:</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="">def condition(x): return x > 10 print(condition(10))
# False print(condition(2))
# False print(condition(11))
# True
</pre>
<p>But you can also define more complicated conditions such as checking if they are prime numbers.</p>
<h3>Python List Count If</h3>
<p><strong>How can you count the elements of the list IF the condition is met?</strong></p>
<p>The answer is to use a simple <a rel="noreferrer noopener" href="https://blog.finxter.com/python-one-line-for-loop-a-simple-tutorial/" target="_blank">generator expression</a> <code>sum(condition(x) for x in lst)</code>:</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="">>>> def condition(x): return x>10 >>> lst = [10, 11, 42, 1, 2, 3]
>>> sum(condition(x) for x in lst)
2</pre>
<p>The result indicates that there are two elements that are larger than 10. You used a generator expression that returns an iterator of Booleans. Note that the Boolean <code>True</code> is represented by the integer value 1 and the Boolean <code>False</code> is represented by the integer value 0. That’s why you can simply calculate the sum over all Booleans to obtain the number of elements for which the condition holds. </p>
<h3>Python List Count Greater / Smaller Than</h3>
<p>If you want to determine the number of elements that are greater than or smaller than a specified value, just modify the condition in this example:</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="">>>> def condition(x): return x>10 >>> lst = [10, 11, 42, 1, 2, 3]
>>> sum(condition(x) for x in lst)
2</pre>
<p>For example, to find the number of elements smaller than 5, use the condition x&lt;5 in the generator expression:</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="">>>> lst = [10, 11, 42, 1, 2, 3]
>>> sum(x&lt;5 for x in lst)
3</pre>
<h3>Python List Count Zero / Non-Zero</h3>
<p>To count the number of zeros in a given list, use the <code>list.count(0)</code> method call.</p>
<p>To count the number of non-zeros in a given list, you should use <em>conditional counting </em>as discussed before:</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="">def condition(x): return x!=0 lst = [10, 11, 42, 1, 2, 0, 0, 0]
print(sum(condition(x) for x in lst))
# 5
</pre>
<h3>Python List Count Lambda + Map</h3>
<p>An alternative is to use a combination of the map and the lambda function. </p>
<p><strong>Related articles:</strong></p>
<ul>
<li><a rel="noreferrer noopener" href="https://blog.finxter.com/how-to-get-rid-of-pythons-map-function-with-list-comprehension/" target="_blank">[Full Tutorial] Map Function</a>: manipulates each element in an iterable.</li>
<li><a rel="noreferrer noopener" href="https://blog.finxter.com/a-simple-introduction-of-the-lambda-function-in-python/" target="_blank">[Full Tutorial] Lambda Function</a>: creates an anonymous function.</li>
</ul>
<p>Here’s the code:</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="">>>> sum(map(lambda x: x%2==0, [1, 2, 3, 4, 5]))
2</pre>
<p>You count the number of even integers in the list. </p>
<ul>
<li>The lambda function returns a truth value for a given element <code>x</code>. </li>
<li>The map function transforms each list element into a Boolean value (1 or 0). </li>
<li>The sum function sums up the “1”s. </li>
</ul>
<p>The result is the number of elements for which the condition evaluates to <code>True</code>.</p>
<h2>Python List Count Regex / Count Matches</h2>
<p>Given a list of strings. How can you check how many list elements match a certain regex pattern? <a rel="noreferrer noopener" href="https://blog.finxter.com/python-regex/" target="_blank">(If you need a refresher on Python regular expressions, check out my ultimate guide on this blo</a><a href="https://blog.finxter.com/python-regex/" target="_blank" rel="noreferrer noopener">g</a><a rel="noreferrer noopener" href="https://blog.finxter.com/python-regex/" target="_blank"> – it’s really ultimate!)</a></p>
<ul>
<li>List <code>lst</code> of string elements</li>
<li>Pattern <code>p</code> to be matched against the strings in the list.</li>
</ul>
<p><strong>Solution</strong>: Use the concept of generator expressions with the ternary operator. </p>
<p><strong>Related articles:</strong></p>
<ul>
<li><a rel="noreferrer noopener" href="https://blog.finxter.com/if-then-else-in-one-line-python/" target="_blank">Master ternary operator.</a></li>
<li><a rel="noreferrer noopener" href="https://blog.finxter.com/list-comprehension/" target="_blank">Master list comprehension.</a></li>
</ul>
<p>Here’s the code:</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="">>>> import re
>>> p = 'a...e'
>>> lst = ['annie', 'alice', 'apex']
>>> sum(1 if re.match(p, x) else 0 for x in lst)
2</pre>
<h2>Python List Count Wildcard</h2>
<p>Do you want to count all string occurrences of a given prefix (e.g. prefix <code>"Sus"</code> for strings <code>"Susie"</code>, <code>"Susy"</code>, <code>"Susi"</code>)?</p>
<p><strong>Solution</strong>: Again you can use the concept of generator expressions with the ternary operator. </p>
<p><strong>Related articles:</strong></p>
<ul>
<li><a rel="noreferrer noopener" href="https://blog.finxter.com/if-then-else-in-one-line-python/" target="_blank">Master ternary operator.</a></li>
<li><a rel="noreferrer noopener" href="https://blog.finxter.com/list-comprehension/" target="_blank">Master list comprehension.</a></li>
</ul>
<p>Here’s the code for this one using the wildcard operator in a pattern to count all occurrences of this pattern in the 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="">>>> import re
>>> lst = ['Susi', 'Ann', 'Susanne', 'Susy']
>>> pattern = 'Sus.*'
>>> frequency = sum(1 if re.match(pattern, x) else 0 for x in lst)
>>> print(frequency)
3</pre>
<p>The generator expression produces a bunch of 1s and 0s—the former if the list element starts with prefix <code>'Sus'</code> and the latter if it doesn’t. By summing over all elements, you get the number of matches of the wildcard operator.</p>
<h2>Where to Go From Here?</h2>
<p>You’ve learned how you can get the number of elements that match a certain condition. It can be a Boolean condition or even a regular expression—the framework stays the same. </p>
<p>Do you want to accelerate your learning efficiency? Do you want to work from the comfort of your own home? Do you want to make a comfortable living by coding 3-5 hours for clients online? </p>
<p>Then join my <a href="https://blog.finxter.com/become-python-freelancer-course/" target="_blank" rel="noreferrer noopener">Python freelancer program</a> and take your first steps towards six figures and attainment of your practical code projects in no time!</p>
<p>Are you still unsure? Watch the<a rel="noreferrer noopener" href="https://blog.finxter.com/webinar-freelancer/" target="_blank"> free software dev online webinar first</a>. It’s fun and you don’t have to have any preknowledge! <img src="https://s.w.org/images/core/emoji/12.0.0-1/72x72/1f60a.png" alt="?" class="wp-smiley" style="height: 1em; max-height: 1em;" /></p>
</div>


https://www.sickgaming.net/blog/2020/03/...condition/
Reply



Forum Jump:


Users browsing this thread:
2 Guest(s)

Forum software by © MyBB Theme © iAndrew 2016