![]() |
|
[Tut] Python: How to Count Elements in a List Matching a Condition? - 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] Python: How to Count Elements in a List Matching a Condition? (/thread-94323.html) |
[Tut] Python: How to Count Elements in a List Matching a Condition? - xSicKxBot - 03-30-2020 Python: How to Count Elements in a List Matching a Condition? 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>3Code: 'a.*'Short answer: you can count the number of elements Code: xCode: condition(x)Code: sum(condition(x) for x in lst)Code: TrueCode: FalseCode: TrueCode: FalseTry it yourself with the interactive code shell: https://repl.it/@finxter/countCondition?lite=true#?secret=Wku9PHjial In case, the browser interpreter doesn’t show up in your browser, here’s the raw Python code: Code: ## 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?Related articles: Python List Count With Condition How can you count elements under a certain condition in Python? 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. Say, you have a condition for each element Code: xCode: condition(x)Code: def condition(x): return x > 10 print(condition(10))
# False print(condition(2))
# False print(condition(11))
# TrueBut you can also define more complicated conditions such as checking if they are prime numbers. Python List Count If How can you count the elements of the list IF the condition is met? The answer is to use a simple generator expression Code: sum(condition(x) for x in lst)Code: >>> def condition(x): return x>10 >>> lst = [10, 11, 42, 1, 2, 3]
>>> sum(condition(x) for x in lst)
2The 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: TrueCode: FalsePython List Count Greater / Smaller Than 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: Code: >>> def condition(x): return x>10 >>> lst = [10, 11, 42, 1, 2, 3]
>>> sum(condition(x) for x in lst)
2For example, to find the number of elements smaller than 5, use the condition x<5 in the generator expression: Code: >>> lst = [10, 11, 42, 1, 2, 3]
>>> sum(x<5 for x in lst)
3To count the number of zeros in a given list, use the Code: list.count(0)To count the number of non-zeros in a given list, you should use conditional counting as discussed before: Code: def condition(x): return x!=0 lst = [10, 11, 42, 1, 2, 0, 0, 0]
print(sum(condition(x) for x in lst))
# 5An alternative is to use a combination of the map and the lambda function. Related articles:
Here’s the code: Code: >>> sum(map(lambda x: x%2==0, [1, 2, 3, 4, 5]))
2You count the number of even integers in the list.
The result is the number of elements for which the condition evaluates to Code: TruePython List Count Regex / Count Matches Given a list of strings. How can you check how many list elements match a certain regex pattern? (If you need a refresher on Python regular expressions, check out my ultimate guide on this blog– it’s really ultimate!)
Solution: Use the concept of generator expressions with the ternary operator. Related articles: Here’s the code: Code: >>> import re
>>> p = 'a...e'
>>> lst = ['annie', 'alice', 'apex']
>>> sum(1 if re.match(p, x) else 0 for x in lst)
2Do you want to count all string occurrences of a given prefix (e.g. prefix Code: "Sus"Code: "Susie"Code: "Susy"Code: "Susi"Solution: Again you can use the concept of generator expressions with the ternary operator. Related articles: Here’s the code for this one using the wildcard operator in a pattern to count all occurrences of this pattern in the list. Code: >>> 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)
3The generator expression produces a bunch of 1s and 0s—the former if the list element starts with prefix Code: 'Sus'Where to Go From Here? 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. 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? Then join my Python freelancer program and take your first steps towards six figures and attainment of your practical code projects in no time! Are you still unsure? Watch thefree software dev online webinar first. It’s fun and you don’t have to have any preknowledge!
|