How to find the length of an iterator?

T

Thorsten Kampe

What is the best way to find out the length of an iterator? len()
doesn't work. In the above code snippet[1] I am only interested in the
index (= length of the iterator), so I'm using len(list(iterator))...

Anything better?

Thanks, Thorsten

[2]
def part(seq, func):
from itertools import takewhile
index = len(list(takewhile(func, seq)))
return [seq[:index], seq[index:]]
 
D

Diez B. Roggisch

Thorsten said:
What is the best way to find out the length of an iterator? len()
doesn't work. In the above code snippet[1] I am only interested in the
index (= length of the iterator), so I'm using len(list(iterator))...

Anything better?

Its the nature of an iterator that it doesn't support anything beyond access
to the current item and signaling when its finished. So if you need the
length, try to get a hold on the underlying connection.
 
D

Diez B. Roggisch

Diez said:
Its the nature of an iterator that it doesn't support anything beyond
access to the current item and signaling when its finished. So if you need
the length, try to get a hold on the underlying connection.

s/connection/collection/

Got confused on my new touchstream dvorak keyboard :)
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

No members online now.

Forum statistics

Threads
474,196
Messages
2,571,036
Members
47,631
Latest member
kukuh

Latest Threads

Top