Monday, 19 January 2009

Today I came across what turned out to be not-so-common need. I wanted to get the length of the generator. Before you comment - yes, I know generators can yield infinite sequences, and that might be one of the reasons why such a function is nowhere to be found. However, if one knows what one's doing it can be of some use. After all, calling list() constructor on iterables is equally risky. Of course, the function is trivial, but managed to give me that that-must-be-somewhere-already feeling. It wasn't :(

def ilen(sequence): result = 0 for _ in sequence: result += 1 return result

I had the exact same thought process, "this has to be somewhere in the standard library", and google took me to this post. The sum(1 for _ in seq) seems most elegant, esp. since I need to filter the elements that I'm counting.