Best way to check that you are at the beginning (the end) of an iterable?
steve+comp.lang.python at pearwood.info
Thu Sep 8 02:24:58 CEST 2011
> Hi there,
> What is the simplest way to check that you are at the beginning or at the
> end of an iterable?
I don't think this question is meaningful. There are basically two
fundamental types of iterables, sequences and iterators.
Sequences have random access and a length, so if the "start" and "end" of
the sequence is important to you, just use indexing:
beginning = sequence
end = sequence[-1]
for i, x in enumerate(sequence):
if i == 0: print("at the beginning")
elif i == len(sequence)-1: print("at the end")
Iterators don't have random access, and in general they don't have a
beginning or an end. There may not be any internal sequence to speak of:
the iterator might be getting data from a hardware device that provides
values continuously, or some other series of values without a well-defined
beginning or end. Example:
from time import asctime
it = time()
What would it even mean to say that I am at the beginning or end of it?
Iterators have no memory, so in one sense you are *always* at the beginning
of the iterator: next() always returns the next item, and the previous item
is lost forever. So the answer to the question "Am I at the beginning of an
iterator?" is always "You are now".
For sequences, the question is best handled differently. For iterators, the
question doesn't make sense in general. If you need an iterator that can
report its internal state, write your own:
import random, time
self.start = True
self.end = False
self.start = False
if random.random() < 0.01:
self.end = True
More information about the Python-list