given an iterable object (such as a list) that was used as the argument of iter() and the value returned from it, and subsequently used, is there a way to determine how many times it has been used, without actually using it any more?
Normally no. Iterators implement only __next__()
and __iter__()
You could call next on
itertools.count
the same amount of times
import itertools
my_list = ['a', 'b', 'c', 'd']
my_iter = iter(my_list)
iter_count = itertools.count()
print(next(iter_count), next(my_iter))
print(next(iter_count), next(my_iter))
Output:
0, a
1, b
If going through the whole iterable use
enumerate
for index, value in enumerate(my_iter):
print(index, value)
Iterators are like BlackBoxes. You've to consume iterators to be able to determine the length.
If the iterator was made from a sequence or a collection, then use this length.
You can also wrap the iterable in more_itertools.countable()
i'll try countable().
i guess this thinking is from my assembly/C upbringing. i was thinking of the iterator i get from iter() as like a pointer moving over the argument (think of next() as incrementing it). if i did p=iter(x)
then i was originally hoping p-x
would give me that count like it would in C. but that operation is not implemented. it has to keep track of where it is so i'm thinking it could be implemented. but few people would ever need it. i haven't until now.