First, to avoid keeping track of a count yourself, you can use enumerate
:
for index, value in enumerate(seq):
Now you'll always know which index goes with the current value
. For example:
>>> for index, value in enumerate(['a', 'b', 'c']):
... print(index, value)
0 a
1 b
2 c
Another alternative is to create an iterator, then loop over that:
it = iter(seq)
for value in it:
Now, the original sequence will still have all of the values, but it
will only have the values you haven't yet looked at.
Or, if you want to, you can manually call next
on it, so you stop at a certain point, or use a function like itertools.takewhile
to do that for you, or…
If you don't want to keep the values at all, you can destructively modify the sequence:
while True:
try:
value = seq.pop(0)
except IndexError:
break
(Note that this one can be slow with large lists, because popping off the beginning has to shift the whole list up. If you can pop from the end instead of the beginning, or use a deque
instead, that problem goes away.)
If you want to, e.g, keep track of how far you got last time so you can pick up from that point next time, either iter
or enumerate
should be enough to do the trick. But if not, you can always store a list of indexes that you've seen so far, or make the list hold [actual_value, False]
pairs and set i[1] = True
when you see them, etc. (That would be a big waste of space—and, more importantly, code complexity—unless you have a good reason for it.)