Python Forum
how far has iteration been run so far?
Thread Rating:
  • 0 Vote(s) - 0 Average
  • 1
  • 2
  • 3
  • 4
  • 5
how far has iteration been run so far?
#1
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?
Tradition is peer pressure from dead people

What do you call someone who speaks three languages? Trilingual. Two languages? Bilingual. One language? American.
Reply
#2
Normally no. Iterators implement only __next__() and __iter__()
Reply
#3
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)
Reply
#4
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.
Almost dead, but too lazy to die: https://sourceserver.info
All humans together. We don't need politicians!
Reply
#5
You can also wrap the iterable in more_itertools.countable()
Reply
#6
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.
Tradition is peer pressure from dead people

What do you call someone who speaks three languages? Trilingual. Two languages? Bilingual. One language? American.
Reply


Forum Jump:

User Panel Messages

Announcements
Announcement #1 8/1/2020
Announcement #2 8/2/2020
Announcement #3 8/6/2020