{"id":110946,"date":"2020-03-29T11:01:06","date_gmt":"2020-03-29T11:01:06","guid":{"rendered":"https:\/\/blog.finxter.com\/?p=7156"},"modified":"2020-03-29T11:01:06","modified_gmt":"2020-03-29T11:01:06","slug":"python-how-to-count-elements-in-a-list-matching-a-condition","status":"publish","type":"post","link":"https:\/\/sickgaming.net\/blog\/2020\/03\/29\/python-how-to-count-elements-in-a-list-matching-a-condition\/","title":{"rendered":"Python: How to Count Elements in a List Matching a Condition?"},"content":{"rendered":"<p>I stumbled across this question when browsing through StackOverflow and it got me thinking: what&#8217;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>\n<figure class=\"wp-block-embed-youtube wp-block-embed is-type-video is-provider-youtube wp-embed-aspect-16-9 wp-has-aspect-ratio\">\n<div class=\"wp-block-embed__wrapper\">\n<div class=\"ast-oembed-container\"><iframe loading=\"lazy\" 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>\n<\/div>\n<\/figure>\n<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>\n<p>Try it yourself with the interactive code shell:<\/p>\n<figure class=\"wp-block-embed-wordpress wp-block-embed is-type-wp-embed is-provider-repl-it\">\n<div class=\"wp-block-embed__wrapper\">\n<iframe loading=\"lazy\" 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>\n<\/div>\n<\/figure>\n<p>In case, the browser interpreter doesn&#8217;t show up in your browser, here&#8217;s the raw Python code:<\/p>\n<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\ndef condition(x): return x > 10 # Create the list\nlst = [10, 11, 42, 1, 2, 3] # Count the number of matching elements\nprint(sum(condition(x) for x in lst))\n# What's the output?<\/pre>\n<p><strong>Related articles:<\/strong><\/p>\n<ul>\n<li><a href=\"https:\/\/blog.finxter.com\/python-list-methods\/\" target=\"_blank\" rel=\"noreferrer noopener\">Python List Methods<\/a><\/li>\n<li><a href=\"https:\/\/blog.finxter.com\/python-list-count\/\" target=\"_blank\" rel=\"noreferrer noopener\">Python List Count()<\/a><\/li>\n<\/ul>\n<h2>Python List Count With Condition<\/h2>\n<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&#8217;s discuss them one by one.<\/p>\n<p>Say, you have a condition for each element <code>x<\/code>. Let&#8217;s make it a function with the name <code>condition(x)<\/code>. You can define any condition you want&#8212;just put it in your function. For example this condition returns True for all elements that are greater than the integer 10:<\/p>\n<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))\n# False print(condition(2))\n# False print(condition(11))\n# True\n<\/pre>\n<p>But you can also define more complicated conditions such as checking if they are prime numbers.<\/p>\n<h3>Python List Count If<\/h3>\n<p><strong>How can you count the elements of the list IF the condition is met?<\/strong><\/p>\n<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>\n<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]\n>>> sum(condition(x) for x in lst)\n2<\/pre>\n<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&#8217;s why you can simply calculate the sum over all Booleans to obtain the number of elements for which the condition holds. <\/p>\n<h3>Python List Count Greater \/ Smaller Than<\/h3>\n<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>\n<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]\n>>> sum(condition(x) for x in lst)\n2<\/pre>\n<p>For example, to find the number of elements smaller than 5, use the condition x&lt;5 in the generator expression:<\/p>\n<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]\n>>> sum(x&lt;5 for x in lst)\n3<\/pre>\n<h3>Python List Count Zero \/ Non-Zero<\/h3>\n<p>To count the number of zeros in a given list, use the <code>list.count(0)<\/code> method call.<\/p>\n<p>To count the number of non-zeros in a given list, you should use <em>conditional counting <\/em>as discussed before:<\/p>\n<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]\nprint(sum(condition(x) for x in lst))\n# 5\n<\/pre>\n<h3>Python List Count Lambda + Map<\/h3>\n<p>An alternative is to use a combination of the map and the lambda function. <\/p>\n<p><strong>Related articles:<\/strong><\/p>\n<ul>\n<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>\n<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>\n<\/ul>\n<p>Here&#8217;s the code:<\/p>\n<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]))\n2<\/pre>\n<p>You count the number of even integers in the list. <\/p>\n<ul>\n<li>The lambda function returns a truth value for a given element <code>x<\/code>. <\/li>\n<li>The map function transforms each list element into a Boolean value (1 or 0). <\/li>\n<li>The sum function sums up the &#8220;1&#8221;s. <\/li>\n<\/ul>\n<p>The result is the number of elements for which the condition evaluates to <code>True<\/code>.<\/p>\n<h2>Python List Count Regex \/ Count Matches<\/h2>\n<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\"> &#8211; it&#8217;s really ultimate!)<\/a><\/p>\n<ul>\n<li>List <code>lst<\/code> of string elements<\/li>\n<li>Pattern <code>p<\/code> to be matched against the strings in the list.<\/li>\n<\/ul>\n<p><strong>Solution<\/strong>: Use the concept of generator expressions with the ternary operator. <\/p>\n<p><strong>Related articles:<\/strong><\/p>\n<ul>\n<li><a rel=\"noreferrer noopener\" href=\"https:\/\/blog.finxter.com\/if-then-else-in-one-line-python\/\" target=\"_blank\">Master ternary operator.<\/a><\/li>\n<li><a rel=\"noreferrer noopener\" href=\"https:\/\/blog.finxter.com\/list-comprehension\/\" target=\"_blank\">Master list comprehension.<\/a><\/li>\n<\/ul>\n<p>Here&#8217;s the code:<\/p>\n<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\n>>> p = 'a...e'\n>>> lst = ['annie', 'alice', 'apex']\n>>> sum(1 if re.match(p, x) else 0 for x in lst)\n2<\/pre>\n<h2>Python List Count Wildcard<\/h2>\n<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>\n<p><strong>Solution<\/strong>: Again you can use the concept of generator expressions with the ternary operator. <\/p>\n<p><strong>Related articles:<\/strong><\/p>\n<ul>\n<li><a rel=\"noreferrer noopener\" href=\"https:\/\/blog.finxter.com\/if-then-else-in-one-line-python\/\" target=\"_blank\">Master ternary operator.<\/a><\/li>\n<li><a rel=\"noreferrer noopener\" href=\"https:\/\/blog.finxter.com\/list-comprehension\/\" target=\"_blank\">Master list comprehension.<\/a><\/li>\n<\/ul>\n<p>Here&#8217;s the code for this one using the wildcard operator in a pattern to count all occurrences of this pattern in the list.<\/p>\n<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\n>>> lst = ['Susi', 'Ann', 'Susanne', 'Susy']\n>>> pattern = 'Sus.*'\n>>> frequency = sum(1 if re.match(pattern, x) else 0 for x in lst)\n>>> print(frequency)\n3<\/pre>\n<p>The generator expression produces a bunch of 1s and 0s&#8212;the former if the list element starts with prefix <code>'Sus'<\/code> and the latter if it doesn&#8217;t. By summing over all elements, you get the number of matches of the wildcard operator.<\/p>\n<h2>Where to Go From Here?<\/h2>\n<p>You&#8217;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&#8212;the framework stays the same. <\/p>\n<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>\n<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>\n<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&#8217;s fun and you don&#8217;t have to have any preknowledge! <img decoding=\"async\" src=\"https:\/\/s.w.org\/images\/core\/emoji\/12.0.0-1\/72x72\/1f60a.png\" alt=\"\ud83d\ude0a\" class=\"wp-smiley\" style=\"height: 1em; max-height: 1em;\" \/><\/p>\n","protected":false},"excerpt":{"rendered":"<p>I stumbled across this question when browsing through StackOverflow and it got me thinking: what&#8217;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. x>3) and regular expressions (e.g. &#8216;a.*&#8217;)? Short answer: you can count the number [&hellip;]<\/p>\n","protected":false},"author":2,"featured_media":0,"comment_status":"open","ping_status":"closed","sticky":false,"template":"","format":"standard","meta":{"footnotes":""},"categories":[857],"tags":[73,468,528],"class_list":["post-110946","post","type-post","status-publish","format-standard","hentry","category-python-tut","tag-programming","tag-python","tag-tutorial"],"_links":{"self":[{"href":"https:\/\/sickgaming.net\/blog\/wp-json\/wp\/v2\/posts\/110946","targetHints":{"allow":["GET"]}}],"collection":[{"href":"https:\/\/sickgaming.net\/blog\/wp-json\/wp\/v2\/posts"}],"about":[{"href":"https:\/\/sickgaming.net\/blog\/wp-json\/wp\/v2\/types\/post"}],"author":[{"embeddable":true,"href":"https:\/\/sickgaming.net\/blog\/wp-json\/wp\/v2\/users\/2"}],"replies":[{"embeddable":true,"href":"https:\/\/sickgaming.net\/blog\/wp-json\/wp\/v2\/comments?post=110946"}],"version-history":[{"count":0,"href":"https:\/\/sickgaming.net\/blog\/wp-json\/wp\/v2\/posts\/110946\/revisions"}],"wp:attachment":[{"href":"https:\/\/sickgaming.net\/blog\/wp-json\/wp\/v2\/media?parent=110946"}],"wp:term":[{"taxonomy":"category","embeddable":true,"href":"https:\/\/sickgaming.net\/blog\/wp-json\/wp\/v2\/categories?post=110946"},{"taxonomy":"post_tag","embeddable":true,"href":"https:\/\/sickgaming.net\/blog\/wp-json\/wp\/v2\/tags?post=110946"}],"curies":[{"name":"wp","href":"https:\/\/api.w.org\/{rel}","templated":true}]}}