Monday, 19 January 2009

ilen for Python

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
BTW. I think itertools is my favourite Python module, what's yours?

8 comments:

Michael Foord said...

You need to blog more!

But your solution consumes the iterator. What if you want to leave it intact?

Why not do: ilen = lambda i: len(list(i))

Konrad said...

I want to avoid constructing a whole list in the memory.

Michael Foord said...

Good enough reason, although won't be as fast. I really like itertools as well - only just starting to learn parts of it.

Some iterators implement __length_hint__ by the way.

Konrad said...

Not generators though (that was my use case).

Jason Scheirer said...

Further itertools abuse:

def iter_length(iterator):
x = (None, 0)
for x in itertools.izip(iterator, itertools.count(1)):
pass
return x[-1]

i0cus said...

Good blog, but why not:

def ilen(seq): return sum(1 for _ in seq)

:)

Konrad said...

@i0cus

Neat :)

openid said...

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.