Python Forum
how far has iteration been run so far? - Printable Version

+- Python Forum (https://python-forum.io)
+-- Forum: Python Coding (https://python-forum.io/forum-7.html)
+--- Forum: General Coding Help (https://python-forum.io/forum-8.html)
+--- Thread: how far has iteration been run so far? (/thread-34042.html)



how far has iteration been run so far? - Skaperen - Jun-21-2021

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?


RE: how far has iteration been run so far? - Gribouillis - Jun-21-2021

Normally no. Iterators implement only __next__() and __iter__()


RE: how far has iteration been run so far? - Yoriz - Jun-21-2021

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)



RE: how far has iteration been run so far? - DeaD_EyE - Jun-21-2021

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.


RE: how far has iteration been run so far? - Gribouillis - Jun-21-2021

You can also wrap the iterable in more_itertools.countable()


RE: how far has iteration been run so far? - Skaperen - Jun-21-2021

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.