python – Efficiently computing size of filtered list – Education Career Blog

I would like to efficiently compute the size of a filtered list, i.e., I don’t want to keep the whole filtered list in memory, I just want to get its size. Is there a more “pythonic” way than computing the size using a for-loop?

For example:

my_list = 1,2,3,4

# this loads the entire **filtered** list in memory
size_of_filtered_list = len(item for item in my_list if item % 2 == 0)

# is there a more pythonic way than this?
size_of_filtered_list = 0
for item in my_list:
    if item % 2 == 0:
        size_of_filtered_list += 1

UPDATE

Apologies if I was not clear. Although the first list (e.g., my_list) is already in memory, I don’t want to create an extra list containing the filtered elements just to count them. I knew about generators and sum but just did not connect the dots… Thanks for your answers.

,

size_of_filtered_list = sum(1 for item in my_list if item % 2 == 0)

,

size_of_filtered_list = sum(item%2==0 for item in my_list)

Leave a Comment