views:

66

answers:

2

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.

+6  A: 
size_of_filtered_list = sum(1 for item in my_list if item % 2 == 0)
gnibbler
+2  A: 
size_of_filtered_list = sum(item%2==0 for item in my_list)
ghostdog74
that creates list doesn't it?
SilentGhost
@SilentGhost: no it doesn't the generator expression is lazy, however gnibbler's solution will be slightly faster, as it is both lazy and sum() wouldn't need to add the zeros.
Lie Ryan
@Lie: you don't seem to be new here, but [anyway](http://stackoverflow.com/posts/3976880/revisions)
SilentGhost
@lie, i was using list comprehension earlier. I changed my answer as i misunderstood the requirement.
ghostdog74
@ghosts: ah, I see, I didn't notice it was edited
Lie Ryan
@ghostdog74 Thanks for your answer. It's readable and looks like what I needed, but I believe (according to my tests) that it is slightly less efficient than gnibbler's answer because the sum has to go through all elements of the filtered list (0+1+0+1) instead of (1+1)
Barthelemy
speed is the least I thought of when i created the answer. I like it to be shorter than gnibbler's. Its entirely up to you to choose the best for your needs.
ghostdog74