Skip to content

Instantly share code, notes, and snippets.

@majorgamerjay
Created October 11, 2020 07:12
Show Gist options
  • Save majorgamerjay/4ffa08716765ee9912f3429e81f20571 to your computer and use it in GitHub Desktop.
Save majorgamerjay/4ffa08716765ee9912f3429e81f20571 to your computer and use it in GitHub Desktop.
Python trick to count the number of items in a list following a certain condition

here's a small trick in python,

let's say you want to count the number of items in a list while following a certain condition, for that you're usually gonna do something like,

this_list = [(some stuff)]
count = 0
for i in this_list:
    if (insert condition):
        count += 1

instead of writing all these, you can use list comprehension with the sum() function,

this_list = [(some stuff)]
count = sum([1 for i in this_list if (insert condition)])

sum() takes all the numbers in a list, and sums it

[1 for i in this_list if (insert condition)], makes it so that, the integer 1 will be appended to the temporary list in sum() everytime the condition is met when the element of this_list is tested so, let's say we got 3 tests succeeded, then,

[1 for i in this_list if (insert condition)] will produce, [1, 1, 1]

for more about list comprehension: https://www.programiz.com/python-programming/list-comprehension

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment